如何在“facet_grid”中向单个 ggplot 图形添加几何形状或注释?
How can I add a geometric shape or an annotation to a single ggplot graphic in `facet_grid`?
我使用 ggplot
制作了多面图,然后尝试使用函数 annotate
仅在绘图的一个特定面板中创建灰色突出显示区域。
我试图从这个问题中调整标签方法,但我无法让它工作:
这是一个可重现的例子:
ggplot(iris, aes(x = Sepal.Length))+
geom_point(aes(y = Petal.Length))+
facet_grid(Species~.)+
annotate(geom = 'rect', xmin = 6, xmax = 6.5, ymin= 0, ymax= Inf,
fill = 'grey20', alpha = 0.2)
输出:
我希望灰色突出显示仅出现在 versicolor
面上,而不是每个面上。
编辑
正如用户@user11362344 所建议的那样,我测试了他使用 geom_rect()
的指示,并添加到代码中 annotate()
和 的位置,效果很好!:
ggplot(data_2, aes(x = Sepal.Length))+
geom_point(aes(y = Petal.Length))+
facet_grid(Species~.)+
geom_rect(data=data.frame(Species='versicolor'), inherit.aes=F,
xmin = 6, xmax = 6.5, ymin = 0, ymax = Inf, fill = 'grey20', alpha = 0.2)
输出:
感谢大家的帮助!特别感谢@user11362344!
geom_rect(data=data.frame(Species='versicolor'), inherit.aes=FALSE,
xmin = 6, xmax = 6.5, ymin= 0, ymax= Inf,
fill = 'grey20', alpha = 0.2)
我使用 ggplot
制作了多面图,然后尝试使用函数 annotate
仅在绘图的一个特定面板中创建灰色突出显示区域。
我试图从这个问题中调整标签方法,但我无法让它工作:
这是一个可重现的例子:
ggplot(iris, aes(x = Sepal.Length))+
geom_point(aes(y = Petal.Length))+
facet_grid(Species~.)+
annotate(geom = 'rect', xmin = 6, xmax = 6.5, ymin= 0, ymax= Inf,
fill = 'grey20', alpha = 0.2)
输出:
我希望灰色突出显示仅出现在 versicolor
面上,而不是每个面上。
编辑
正如用户@user11362344 所建议的那样,我测试了他使用 geom_rect()
的指示,并添加到代码中 annotate()
和 的位置,效果很好!:
ggplot(data_2, aes(x = Sepal.Length))+
geom_point(aes(y = Petal.Length))+
facet_grid(Species~.)+
geom_rect(data=data.frame(Species='versicolor'), inherit.aes=F,
xmin = 6, xmax = 6.5, ymin = 0, ymax = Inf, fill = 'grey20', alpha = 0.2)
输出:
感谢大家的帮助!特别感谢@user11362344!
geom_rect(data=data.frame(Species='versicolor'), inherit.aes=FALSE,
xmin = 6, xmax = 6.5, ymin= 0, ymax= Inf,
fill = 'grey20', alpha = 0.2)