1

I have a series of daily data for several years

df <- data.frame(date = seq.Date(from = as.Date('2020-01-01'), to = as.Date('2020-12-31'), by = 'day'),
                 value = runif(366))

I'd like to have the background colour to change every month, alternating from white to light grey. I've tried using ifelse inside theme but it did not work (apparently it takes the result for the first line and repeats along the whole plot).

library(ggplot2)

ggplot(df, aes(x = date, y = value))+
    geom_line()+
    scale_x_date(breaks = 'month', expand = c(0,0))+
    theme(panel.background = element_rect(ifelse(lubridate::month(df$date) %% 2 == 0, 'white', 'grey')))
Pedro Alencar
  • 1,049
  • 7
  • 20
  • 1
    I've seen folks make rectangles in `geom_rect()` to do this like [in this answer](https://stackoverflow.com/a/10565733/2461552) – aosmith Aug 02 '21 at 16:00
  • That's a solution. although not what I wanted haha! Thanks! – Pedro Alencar Aug 03 '21 at 08:04
  • I am also trying to do this, basically alternating between white and light grey for each month but I have to plot for each individual and their starting and ending values are different. I can't find anything that is flexible to handle this and have been looking for several hours! – A. C. Del Re Jul 06 '23 at 22:53

0 Answers0