这里是一个例子:
library(ggplot2)
set.seed(123)
df<-data.frame(sid=letters[1:8],
groups=rep(1:4, each=2),
blp=abs(rnorm(8, 120, 5)),
bmi=abs(rnorm(8, 25, 5)),
gender=rep(c("F", "M"), each=4))
ggplot(df, aes(bmi, blp))+
geom_point(size=2)+
facet_grid(sid~groups)
答案 0 :(得分:2)
library(ggplot2)
set.seed(123)
df<-data.frame(sid=letters[1:8],
groups=rep(1:4, each=2),
blp=abs(rnorm(8, 120, 5)),
bmi=abs(rnorm(8, 25, 5)),
gender=rep(c("F", "M"), each=4))
ggplot(df, aes(bmi, blp, color = gender))+
geom_point(size=2)+
facet_grid(sid~groups)
ggplot(df, aes(bmi, blp, color = gender))+
geom_point(size=2)+
facet_grid(sid~groups)+
geom_rect(data=subset(df, gender == "F"),
aes(xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf),
fill="red", alpha=0.2)+
geom_rect(data=subset(df, gender == "M"),
aes(xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf),
fill="blue", alpha=0.2)
一个更简单的解决方案是+ geom_rect(aes(xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf, fill = gender), alpha=0.2)
而不是两个geom_rect()
。
注意:正如其他人指出的那样,有很多方法可以使您的情节风格化,但是这些方法非常混乱。上面的解决方案既简单又干净,但是显然只能填充包含数据的方面。
答案 1 :(得分:2)
您可以将ggplot转换为grob,并在其中进行更改:
# convert to grob
gp <- ggplotGrob(p) # where p is the original ggplot object
# assign the first 4 right-side facet strips with blue fill
for(i in 1:4){
grob.i <- grep("strip-r", gp$layout$name)[i]
gp$grobs[[grob.i]]$grobs[[1]]$children[[1]]$gp$fill <- "blue"
}
# assign the next 4 right-side facet strips with red fill
for(i in 5:8){
grob.i <- grep("strip-r", gp$layout$name)[i]
gp$grobs[[grob.i]]$grobs[[1]]$children[[1]]$gp$fill <- "red"
}
grid::grid.draw(gp)
答案 2 :(得分:1)