0

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 ?

Chika
  • 1,455
  • 2
  • 16
  • 24
  • Might be useful: https://stackoverflow.com/questions/9968975/make-the-background-of-a-graph-different-colours-in-different-regions – Skaqqs Jan 13 '22 at 16:36
  • As referenced in the link above, you can probably set `alpha=0.2` and the fill color to something darker to allow you to see the grid through the rectangles. You may have to adjust the color or linewidth of the grid to compensate, but it's probably the simplest solution. – chemdork123 Jan 13 '22 at 23:46
  • Thanks a lot ! "alpha" didn't work with geom_rect so I had to use "+ annotate("rect", xmin=2.5, xmax=3.5, ymin = -Inf, ymax = Inf, fill="gray20", alpha = 0.2)" and now it works – Chika Jan 14 '22 at 13:03

1 Answers1

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

Chika
  • 1,455
  • 2
  • 16
  • 24