Update 2023:
There is now a great package, ggh4x
by @teunbrand
See this answer to the related the question
Q: In a ggplot, how can we modify the colors of the facet background based on the group.
Can there be more than one color for facet backgrounds?
Example:
I am using facet_grid
(not facet_wrap
) with multiple layers.
## Sample data
dat <- mtcars
## Add in some colors based on the data
dat$facet_fill_color <- c("red", "green", "blue", "yellow", "orange")[dat$gear]
## Create main plot
library(ggplot2)
P <-
ggplot(dat, aes(x = cyl, y = wt)) +
geom_point(aes(fill = hp)) +
facet_grid(gear + carb ~ .)
The background of ALL of the strips can be changed using:
P + theme(strip.background = element_rect(fill="red"))
main challenge:
However, I would like to change the color differently for different groups.
Something like the following (which of course does not work)
P + theme(strip.background = element_rect(fill=dat$facet_fill_color))
P + theme(strip.background = element_rect(aes(fill=facet_fill_color)))
related, but not an actual answer to this current question ggplot2: facet_wrap strip color based on variable in data set)