Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set x-axis ticks to month ends?

I am trying to set x-axis ticks to month ends in ggplot2. Currently the plot generated has ticks that correspond to the first of the month. The code I am using to generate the scale is

p + scale_x_date(limits = c(as.Date("2006-12-31"), as.Date("2014-09-30")), date_breaks = "6 months", date_labels = "%Y-%m-%d")

I would have thought that since my limits are month ends it ticks would also be month ends. Furthermore, my data starts on 2007-01-02 so the first tick is 2007-02-01. I would like to set the ticks in line with quarter ends.

like image 667
Harry O'Reilly Avatar asked Oct 22 '25 08:10

Harry O'Reilly


1 Answers

One way to get the exact axis breaks you want is to specify them explicitly by supplying a vector of dates to the breaks argument in scale_x_date. You haven't provided a reproducible example, so I've plotted some fake data. In the code below, I've specified breaks at the end of each quarter. I needed to subtract one day from each of the 30-day months, so that the break would be on the last day of the quarter, rather than on the first day of the next quarter.

# Fake data
dat = data.frame(date=seq(as.Date("2006-12-31"), as.Date("2014-09-30"), by="1 day"))
set.seed(495)
dat$value = cumsum(rnorm(nrow(dat)))

ggplot(dat, aes(date, value)) + 
  geom_line() + 
  scale_x_date(limits = c(as.Date("2006-12-31"), as.Date("2014-09-30")), 
               breaks = seq(as.Date("2006-03-31"), as.Date("2014-12-31"), "quarter") - c(0,1,1,0),
               date_labels = "%Y-%m-%d", expand=c(0,30)) +
  theme(axis.text.x=element_text(angle=-90, vjust=0.5))

enter image description here

like image 85
eipi10 Avatar answered Oct 23 '25 21:10

eipi10



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!