我想根据组修改构面背景的颜色.我不确定这是否可行.具体来说,我使用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 ~ .)
## I can easily cahnge the background using:
P + theme(strip.background = element_rect(fill="red"))
Run Code Online (Sandbox Code Playgroud)
但是,我想为不同的组改变颜色.理想情况下,如下所示(当然不起作用)
P + theme(strip.background = element_rect(fill=dat$facet_fill_color))
P + theme(strip.background = element_rect(aes(fill=facet_fill_color)))
Run Code Online (Sandbox Code Playgroud)
小平面背景可以有多种颜色吗?
(相关,但不是上面的实际答案: ggplot2:基于数据集中变量的facet_wrap条带颜色)
我想根据特定列中给出的值为ggplot2 facet图的背景着色.使用我已经问过的先前问题的答案,我能够将我需要的东西拼凑在一起.@joran对这个问题的回答特别有用,因为它说明了创建一个单独的数据框以传递给ggplot的技术.
这一切都很好,给出了如下图所示的输出:

这是我用来生成上图的代码:
# User-defined variables go here
list_of_names <- c('aa','bb','cc','dd','ee','ff')
list_of_regions <- c('europe','north america','europe','asia','asia','japan')
# Libraries
require(ggplot2)
require(reshape)
# Create random data with meaningless column names
set.seed(123)
myrows <- 30
mydf <- data.frame(date = seq(as.Date('2012-01-01'), by = "day", length.out = myrows),
aa = runif(myrows, min=1, max=2),
bb = runif(myrows, min=1, max=2),
cc = runif(myrows, min=1, max=2),
dd = runif(myrows, min=1, max=2),
ee = runif(myrows, min=1, max=2),
ff = runif(myrows, min=1, max=2))
# Transform data frame from …Run Code Online (Sandbox Code Playgroud)