Jessi
Jessi

Reputation: 33

ggplot2 dates x-axis

I am plotting a monthly time series (dat1 which contains a column for cold) with a date on the x-axis. The date is defined as a monthly sequence:

seq(as.Date("1936/01/01"), as.Date("2013/01/01"), by="months")

When generating the plot using

g=ggplot(data=dat1, aes(x=date, y=cold))+ geom_line()+ scale_x_date()

I am getting dates on the x-axis as 1940, 1960, 1980, ... till 2000, I was wondering if I can get the dates every 10 years from 1940 to 2010 inclusive on the x-axis.

How to change the dates on the x-axis?

Upvotes: 2

Views: 1837

Answers (1)

Hack-R
Hack-R

Reputation: 23221

From the ?scale_x_date help page:

breaks    
One of:
NULL for no breaks
waiver() for the default breaks computed by the transformation object
A numeric vector of positions
A function that takes the limits as input and returns breaks as output

Date labels for x-axis from 1940 to 2000 inclusive:

dat1 <-  data.frame(
  cold = rep(c(0,25,14,18,22),925/5),
  date = seq(as.Date("1936/01/01"), as.Date("2013/01/01"), by="months"))


ggplot(data=dat1, aes(x=date, y=cold))+ 
  geom_line()+ 
  scale_x_date(breaks = seq(dat1$date[lubridate::year(dat1$date)=="1940"][1],
                            dat1$date[lubridate::year(dat1$date)=="2000"][1],
                            by="10 years")) 

enter image description here

Upvotes: 0

Related Questions