1

I would like to change the background color of specific facets in a ggplot arranged as a facet_grid.

test <- tibble(rows = c("C", "D","C", "D"),
               cols = c("A", "B", "B", "A"),
               x = c(1, 1, 1, 1),
               y = c(1, 1, 1, 1))

ggplot(test) +
  geom_point(aes(x = x, y = y)) +
  facet_grid(vars(rows), vars(cols)) +
  theme_minimal() +
  theme(
    panel.grid.major.y = element_blank(),
    panel.grid.minor.y = element_blank(),
    panel.background = element_rect(fill = NA, color = "grey60")
  )

For example, if it were possible to make specifically facet AC have a red panel background color while the others are grey.

I've seen some ways of drilling down into the grob object to do something like this with the strip background (https://github.com/tidyverse/ggplot2/issues/2096) but I can't work out how to get this kind of thing to work for different parts of the plot.

Any help would be great!

Jamie
  • 401
  • 3
  • 11

1 Answers1

1

Perhaps you prefer a solution like this, no grob manipulation necessary:

ggplot(test) +
  geom_rect(
    aes(xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf), 
    data.frame(rows = 'C', cols = 'A'),
    fill = 'red', alpha = 0.5
  ) +
  geom_point(aes(x = x, y = y)) +
  facet_grid(vars(rows), vars(cols)) +
  theme_minimal() +
  theme(
    panel.grid.major.y = element_blank(),
    panel.grid.minor.y = element_blank(),
    panel.background = element_rect(fill = NA, color = "grey60")
  )

enter image description here

A downside is that the color is drawn on top of the grid lines. Some transparency as used above is usually a good solution. Alternatively, you can use theme(panel.ontop = TRUE) to draw the grid lines on top, but then they will also be plotted on top of the data.

Axeman
  • 32,068
  • 8
  • 81
  • 94
  • You can usually make one data.frame with one `geom_rect` call, like shown here: https://stackoverflow.com/questions/9847559/conditionally-change-panel-background-with-facet-grid. Not sure if the grob alternative would be any easier.. – Axeman May 11 '22 at 15:42