2

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?

Jessi
  • 33
  • 7
  • 1
    You can set the breaks manually in `scale_x_date()` to get breaks set at specific locations: `breaks = seq(as.Date("1940/01/01"), as.Date("2010/01/01"), by="10 years")`. Often you could use `date_breaks` instead for convenience but that doesn't necessarily start things at the right place. You'll likely also need set your `date_labels` a la `date_labels = "%Y"` if you only want labels for years only. – aosmith Jun 15 '18 at 15:54
  • @Jessi: see this [answer](https://stackoverflow.com/a/50710428/786542) for examples – Tung Jun 16 '18 at 02:31

1 Answers1

0

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

Hack-R
  • 22,422
  • 14
  • 75
  • 131