Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Annotate first month with year in ggplot2

Tags:

r

ggplot2

Suppose I have a plot like this:

DF <- data.frame(date=Sys.Date() - (-100):100, y=rnorm(201))
library("ggplot2")
library(scales)
ggplot(DF, aes(x=date, y=y)) +
 geom_point() +
 scale_x_date(breaks = "1 month", minor_breaks = "1 week", labels=date_format("%b"))

Here I want to include major lines and labels at every month and minor lines at every week. This works well, but now I would like to include the year behind the abbreviated month, but only for the first month of that year in the plot. Thus, the labels should read sep 2014. okt, nov, dec, jan 2015, feb, mrt....

Is this possible?

like image 907
Sacha Epskamp Avatar asked Dec 09 '14 13:12

Sacha Epskamp


1 Answers

You can do it with a custom date formatter to remove duplicated years:

my_date_format <- function()
{
   function(x)
   {
       m <- format(x,"%b")
       y <- format(x,"%Y")
       ifelse(duplicated(y),m,paste(m,y))
   }
}

ggplot(DF, aes(x=date, y=y)) +
 geom_point() +
 scale_x_date(breaks = "1 month", minor_breaks = "1 week", labels=my_date_format())

Custom date plot

like image 124
James Avatar answered Nov 03 '22 13:11

James