How to set different panel color in individual facet?

Hi, I am trying to create facet plot and want to set different panel background color for each plot in order to classify the individual facets into two or three groups.

For example,

library(ggplot2)
dat <- expand.grid(list(
  x = letters[1:3],
  y = LETTERS[1:4], 
  z = c("M1", "M2", "M3")
))
dat$value <- rnorm(36)

ggplot(dat, aes(z,value)) +
  geom_point() +
  geom_line(group = 1) +
  facet_grid(x ~ y)


How can I set different panel backgroud color for each plot? Thanks!

Here is a hack that might get you what you need. I requires making a data frame with your faceting variables, assigning each row to a group, and using that group as the fill variable.

library(ggplot2)
dat <- expand.grid(list(
  x = letters[1:3],
  y = LETTERS[1:4], 
  z = c("M1", "M2", "M3")
))
dat$value <- rnorm(36)
  
  dat2 <- expand.grid(list(
    x = letters[1:3],
    y = LETTERS[1:4]))
dat2$Grp <- sample(c("Good","Bad", "Ugly"),12,replace = TRUE)  

ggplot(dat, aes(z,value)) +
  geom_point() +
  geom_line(group = 1) +
  geom_rect(aes(fill = Grp),data = dat2, inherit.aes = FALSE,
            xmin=-Inf, xmax=Inf, ymin = -Inf, ymax=Inf, alpha = 0.2) +
  facet_grid(x ~ y)

Created on 2024-11-04 with reprex v2.1.1

2 Likes

Thanks a lot! It's very helpful!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.