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

Jam*_*mes 10 r ggplot2

在vanilla plotting中,可以polygonpanel.first参数中使用调用plot来突出显示背景区域.是否可以这样做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)))
Run Code Online (Sandbox Code Playgroud)

rcs*_*rcs 17

是的,这可能与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()
Run Code Online (Sandbox Code Playgroud)

ggplot2输出