An Ad
An Ad

Reputation: 3

How to label all the data points in the x-axis?

I have a df that looks like this:

Year Type n
2012 PTS 1
2012 POS 2
2013 POS 4
2013 PTS 6
2014 PTS 5
2014 PTS 6
2015 POS 3
2015 PTS 8
2016 POS 10
2016 PTS 11

I am trying to make a line graph with year in the x-axis.

I tried making a geom_line graph using:

df%>%
  ggplot()+
  geom_line(aes(x=Year, y= n, color= `Type`))
  

However, I don't get all the labels on the x-axis of my graph. My df has many years and it shows me years in the x-axis in the intervals of 5. I tried using the code below but I get "Error in check_breaks_labels(breaks, labels) : object 'Year' not found"

df%>%
  ggplot()+
  geom_line(aes(x=Year, y= n, color= `Type`))+
  scale_x_continuous("Year", labels = as.character(Year), breaks = Year)

How could I fix it?

Upvotes: 0

Views: 369

Answers (1)

AndrewGB
AndrewGB

Reputation: 16856

Another option is to create a sequence from the min and max of the Year column.

library(tidyverse)

df %>%
  ggplot() +
  geom_line(aes(x = Year, y = n, color = `Type`)) +
  scale_x_continuous(breaks = seq(min(df$Year), max(df$Year), 1))

Output

enter image description here

Data

df <- structure(list(Year = c(2012L, 2012L, 2013L, 2013L, 2014L, 2014L, 
2015L, 2015L, 2016L, 2016L), Type = c("PTS", "POS", "POS", "PTS", 
"PTS", "PTS", "POS", "PTS", "POS", "PTS"), n = c(1L, 2L, 4L, 
6L, 5L, 6L, 3L, 8L, 10L, 11L)), class = "data.frame", row.names = c(NA, 
-10L))

Upvotes: 1

Related Questions