Search code examples
rggplot2data-visualizationfacet-grid

Change panel background color of specific ggplot facets


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!


Solution

  • 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.