Insert a grid between two elements with ggplot in R

I am trying to overlay the background of my plot with a color depending on the x-axis, with geom_rect. For example, for x-values between 0.5 and 1.5, background will be grey. It will be white for x-values between 1.5 and 2.5, then grey, etc. I also have a grid and boxplots on my plot.

I want for the grid to be ontop of this colored background but behind the boxplots.

p <- (p
      + theme_bw()
      + ggtitle(dates[i])
      + xlab("Echeance")
      + geom_rect(xmin=0.5, xmax=1.5, ymin=500, ymax=7500, fill="gray90")
      + geom_rect(xmin=1.5, xmax=2.5, ymin=500, ymax=7500, fill="gray100")
      + geom_rect(xmin=2.5, xmax=3.5, ymin=500, ymax=7500, fill="gray90")
      
      + geom_line(data=data, aes(x=Var3, y=value), group=1)
      + geom_boxplot(aes(linetype=exp))
      + guides(linetype="none")
      + scale_y_continuous(n.breaks = 20))

Without options, I have the colored background ontop of the grid, and behind the boxplots.

enter image description here

If I add

 + theme(panel.ontop = TRUE, panel.background = element_rect(fill = NA))

Then I have the grid ontop the colored background but also on top of the boxplot...

enter image description here

Does someone has the trick ?


Solution 1:

Use (instead of geom_rect)

+ annotate("rect", xmin=2.5, xmax=3.5, ymin = -Inf, ymax = Inf, fill="gray20", alpha = 0.2)

with alpha controling the transparency