在ggplot2中突出显示感兴趣的区域

11
在传统绘图中,可以在plot函数的panel.first参数中使用polygon函数来突出显示背景区域。在ggplot2中是否也可以这样做?能否在保留网格线的同时完成这个功能?
例如:
# plot hp and wt for mtcars data, highlighting region where hp/wt ratio < 35
with(mtcars,plot(hp,wt,
     panel.first=polygon(c(0,0,max(wt)*35),c(0,max(wt),max(wt)),
     col="#d8161688",border=NA)))
1个回答

18

使用ggplot2是可以实现的。为保持网格线的可见性,您可以使用alpha透明度。需要注意的是,在一般情况下,应用geoms和stats的顺序是很重要的。

tmp <- with(mtcars, data.frame(x=c(0, 0, max(wt)*35), y=c(0, max(wt), max(wt))))
ggplot(mtcars, aes(hp, wt)) + 
  geom_polygon(data=tmp, aes(x, y), fill="#d8161688") + 
  geom_point()

ggplot2输出


rcs,这很酷,但是你能解释一下为什么这种颜色是透明的吗?谢谢! - rrs
由于RGB字符串中的最后2个数字(0=完全透明,FF=不透明,请参见?rgb); 人们也可以在geom_polygon中使用alpha美学。 - rcs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接