一种使用grid
函数编辑您的plot
的方法。
在grid
视口中绘制一个矩形很容易。是否可能构造一个grid
视口,使其完全覆盖ggplot面板集?答案是“是”。对于绘制矩形的技巧是从ggplot_build
信息中获取x轴“本地”坐标到grid视口中。
library(ggplot2)
library(grid)
plot <- ggplot(mpg, aes(displ, hwy)) +
geom_point() +
facet_grid(class ~ .)
plot
gt = ggplotGrob(plot)
lay = grid.layout(nrow = length(gt$heights), ncol = length(gt$widths),
widths = gt$widths, heights = gt$heights)
pushViewport(viewport(layout = lay))
pos = gt$layout[grep("panel", gt$layout$name), c("t", "l")]
pushViewport(viewport(layout.pos.col = pos$l, layout.pos.row = min(pos$t):max(pos$t)))
x.axis.limits = summarise_layout(ggplot_build(plot))[1, c('xmin', 'xmax')]
pushViewport(dataViewport(yscale = c(0, 1),
xscale = x.axis.limits))
grid.rect(x = 3, y = 0,
width = 1, height = 1,
just = c("left", "bottom"), default.units = "native",
gp = gpar(fill = "green", col = "transparent", alpha = .2))
upViewport(0)
![enter image description here](https://istack.dev59.com/xJ0EM.webp)