在ggplot2中做任何事情的一般规则是,
- 创建一个数据框,对您要绘制的信息进行编码
- 将该数据框传递给几何对象
在这种情况下,由于您要更改的情节的特定方面,这会变得更加复杂。设计的权力 ggplot2 以将绘图的数据元素(即geom's)与非数据元素(即主题)分开的方式,并且恰好情节背景属于“非-数据”类别。
总是有修改底层网格对象manually的选项,但这很乏味,细节可能会随着ggplot2的不同版本而改变。相反,我们将使用 Hadley 在this 问题中提到的“hack”。
#Create a data frame with the faceting variables
# and some dummy data (that will be overwritten)
tp <- unique(tips[,c('sex','day')])
tp$total_bill <- tp$tip <- 1
#Just Fri
ggplot(tips,aes(x=total_bill, y = tip/total_bill)) +
geom_rect(data = subset(tp,day == 'Fri'),aes(fill = day),xmin = -Inf,xmax = Inf,
ymin = -Inf,ymax = Inf,alpha = 0.3) +
geom_point(shape=1) +
facet_grid(sex ~ day)
#Each panel
ggplot(tips,aes(x=total_bill, y = tip/total_bill)) +
geom_rect(data = tp,aes(fill = day),xmin = -Inf,xmax = Inf,
ymin = -Inf,ymax = Inf,alpha = 0.3) +
geom_point(shape=1) +
facet_grid(sex ~ day)