user3022875 user3022875 - 10 days ago 4
R Question

ordering of date on xaxis after format

I have this plot:

I am using scale_x_date to get the format to the dates "MON DD" on the axis below but I don't want to change the date ONLY the format. So I'd like "Jan 01", "Jan 08", "Jan 15", "Jan 22" on the x axis instead of "Jan 04", "Jan 11" etc..... Is that possible?

library(scales)
library(ggplot2)
d = data.frame(date = as.Date(c("2016-01-22", "2016-01-01")),value= c(1,2))
ggplot(d, aes(
x=date,
#x= factor(format(as.Date(date),"%b %d"),levels = unique( format(as.Date(date),"%b %d") ) ),
y = value,group=1))+
geom_point() + scale_x_date(date_label="%b %d", date_breaks = "1 week") +
geom_line()+xlab("date")

Answer

I'm not sure why the default ticks are as they appear, but this should do the trick:

dts <- seq(from = as.Date("2016-01-01"),to = as.Date("2016-01-28"), by = 7)
ggplot(d, aes(x=date, y = value,group=1)) +
  geom_point() + scale_x_date(labels=format(dts,"%b %d"), breaks = dts) +
  geom_line()+xlab("date")
Comments