rggplot2background-colorfacetstrip

Change the strip text background color based on a grouping variable that's not used in facet_wrap (ggplot2)?


I am wondering if there are any ways to change the background colour of strip text by the grouping variable (group2) which is not in the faceting variable (group1) in ggplot. For example, in the plot shown below, I would like to change the color of upper background (G1, G2) to red and the lower background (G3, G4) to blue same as point colors.

# Data simulation
library(dplyr);library(ggplot2)
set.seed(1)
x <- runif(500)
y <- 4 * x^2 + rnorm(length(x), sd = 5)
group1 <- ifelse(x < 0.4, "G1", ifelse(x < 0.6, "G2", ifelse(x < 0.8, "G3", "G4")))

x <- x + runif(length(x), -0.5, 0.5)

  df <- data.frame(x = x, y = y, group1 = group1) |> 
  dplyr::mutate(group2=ifelse(group1 %in% c("G1","G2"), "A", "B"))

  ggplot(df, aes(x = x, y = y)) +
  theme_bw()+
  geom_point(aes(x = x, y = y, colour = factor(group2)), show.legend = FALSE, size=3) +
  scale_colour_manual(values = c("red","blue"))+
  facet_wrap(. ~ group1) +
  theme(strip.text = element_text(face = "bold",size = 12,margin = margin(b = 1.2)))

enter image description here


Solution

  • One option to have different fill colors for the strip background would be to use the ggh4x package. In the code below I simply hard-coded the colors. But for more complicated stuff it would also be possible to use a color mapping.

    library(ggplot2)
    library(ggh4x)
    
    ggplot(df, aes(x = x, y = y)) +
      theme_bw() +
      geom_point(aes(x = x, y = y, colour = factor(group2)),
        show.legend = FALSE, size = 3
      ) +
      scale_colour_manual(values = c("red", "blue")) +
      ggh4x::facet_wrap2(. ~ group1,
        strip = ggh4x::strip_themed(
          background_x = ggh4x::elem_list_rect(
            fill = c(rep("red", 2), rep("blue", 2))
          ),
          text_x = element_text(color = "white")
        )
      ) +
      theme(strip.text = element_text(
        face = "bold",
        size = 12, margin = margin(b = 1.2)
      ))