0

One would like to colour the background of selected facet_wrap facets using the theme and panel.background arguments, as explained here. However, as explained here, theme doesn't map onto data, so one is forced to colour selected facets using geom_rect and fill, and making the alpha quite transparent.

The code below works. However, I find that the colouring isn't pretty, especially when dealing with large data that forces increasing the transparency.

mtcars %>%
  ggplot(aes(mpg, cyl)) +
  facet_wrap(~gear) +
  geom_point() +
  geom_rect(data = mtcars %>% filter(gear == 3), fill = 'red',
            xmin = -Inf,xmax = Inf,
            ymin = -Inf,ymax = Inf,
            alpha = 0.003)

enter image description here

Is there an alternative way of colouring selected facets, ideally using theme and panel.background?

NBK
  • 887
  • 9
  • 20
  • I don't know another workaround, but this would look better if you 1) specify the gray as well as the red, so the red doesn't have both, and 2) use `annotate` or a summarized data set so each facet only gets one layer. – Jon Spring Jun 20 '22 at 14:17
  • short answer: yes there are alternative ways, but not with theme or panel.background. You also don't really wanna use those other ways, as this will mean changing the underlying grobs. Your way is the most straightforward and actually also not much of a hack. – tjebo Jun 20 '22 at 14:34
  • @JonSpring by modifying the gray, you mean removing the default gray background? In my actual graph, I'm using a theme_classic, so the default background is white. But still, the geom_rect fills get a strange greyish tone, and I don't know why. Maybe your suggestion alludes to that fact. – NBK Jun 20 '22 at 14:57

0 Answers0