问题描述
我正在使用 ggplot2 中的提示"数据集.如果我这样做
I'm using the "tips" data set in ggplot2. If I do
sp = ggplot(tips,aes(x=total_bill, y = tip/total_bill)) +
geom_point(shape=1) +
facet_grid(sex ~ day)
情节很好.但我现在只想更改星期五"下的图的面板背景.有没有办法做到这一点?
The plot comes out fine. But I now want to change the panel background for just the plots under "Fri". Is there a way to do this?
更好的是,我可以通过传递参数有条件地改变颜色吗?例如,如果超过 3 个点低于 0.1,那么将面板背景(仅针对该面板)更改为某种颜色,而所有其他颜色都保持默认的浅灰色?
Even better, can I conditionally change colors by passing parameters? For example if more than 3 points are below 0.1, then change panel background (for just that panel) to a certain color while all others remain the default light grey?
推荐答案
在 ggplot2 中做任何事情的一般规则是,
The general rule for doing anything in ggplot2 is to,
- 创建一个数据框,对您要绘制的信息进行编码
- 将该数据框传递给 geom
在这种情况下,由于您要更改的情节的特定方面,这会变得更加复杂.设计的权力 ggplot2 以将情节的数据元素(即 geom 的)与非数据元素(即主题的)分开的方式,并且恰好情节背景属于非-数据"类别.
This is made a bit more complicated in this case because of the particular aspect of the plot you want to alter. The Powers That Be designed ggplot2 in a way that separates data elements of the plot (i.e. geom's) from non-data elements (i.e. theme's), and it so happens that the plot background falls under the "non-data" category.
总有修改底层网格对象的选项 手动 但这很乏味,而且细节可能会随着 ggplot2 的不同版本而改变.相反,我们将使用 Hadley 在这个问题中提到的hack".
There is always the option of modifying the underlying grid object manually but this is tedious and the details may change with different versions of ggplot2. Instead, we'll employ the "hack" that Hadley refers to in this question.
#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)
这篇关于使用 facet_grid 有条件地更改面板背景?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!