2023年更新:
现在有一个很棒的软件包,由@teunbrand开发的ggh4x
请参阅这个答案以了解相关问题
问题:在ggplot中,我们如何根据组修改facet背景的颜色?
facet背景可以有多种颜色吗?
示例:
我正在使用facet_grid(而不是facet_wrap)与多个图层。
## 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 ~ .)
所有条纹的背景都可以使用以下方法进行更改:
P + theme(strip.background = element_rect(fill="red"))
主要挑战:
然而,我想为不同的群体以不同的颜色进行更改。
类似以下的方式(当然是无效的)
P + theme(strip.background = element_rect(fill=dat$facet_fill_color))
P + theme(strip.background = element_rect(aes(fill=facet_fill_color)))
相关,但不是对当前问题的实际答案 ggplot2:根据数据集中的变量设置facet_wrap条纹颜色)