Question

I'm trying to add ticks between the months on the x-axis using ggplot2 - something like this:

enter image description here

instead of the standard ticks at the months.

My process thus far has been as follows (for example):

y=(1:1:12)
x=seq(as.Date("2014-01-01"), as.Date("2014-12-31"), by="months")
df=data.frame(x,y)
g<-ggplot(df,aes(x,y))
g<-g+geom_line()
g<-g+scale_x_date(labels = date_format("%b-%y"),breaks = date_breaks("months"))

Which gives me:

enter image description here

I'd like those x-axis ticks to be between the months. I've tried using

 minor_breaks=date_breaks("2 weeks")

in the scale_x_date line (along with several other variations), but the minor_breaks doesn't seem to be working for me. I've also tried variations of

 myminor=seq(from=1,to=365,by=15)

and using that for minor_breaks, but that didn't work either. Finally, I tried

g<-g+theme(axis.ticks.x=element_line(myminor))

but that also proved ineffective. I feel like it's a simple fix but I'm stuck.

Was it helpful?

Solution

Fairly hacky, but somewhat closer to what you seem to want:

library(ggplot2)
library(scales)
library(lubridate)
y=(1:12)
x=seq(as.Date("2014-01-01"), as.Date("2014-12-31"), by="months")
df=data.frame(x,y)
g<-ggplot(df,aes(x,y))
g<-g+geom_line()

labels <- date_format("%b")(x)
breaks <- as.Date(sort(c(as.POSIXct(x), 
                         as.POSIXct(seq(as.Date("2014-01-15"), 
                                        as.Date("2014-12-31"), by="months")),
                         ymd("2015-1-1"))))
labels <- c("", 
            as.vector(rbind(labels, 
                            rep("", length(labels)))))

g + scale_x_date(labels = labels, breaks = breaks, limits=range(breaks)) + 
    theme(axis.ticks.x=element_line(colour=c("black", 
                                             rep(c(NA, "black"), t=12))),
          panel.grid.major.x=element_line(colour=c("white", 
                                                   rep(c(NA, "white"), t=12))),
          panel.grid.minor.x=element_blank())

Imgur

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top