首页 > 解决方案 > 如何使用 ggplotGrob 和 annotation_custom 将 grob 与 ggplot 对齐?

问题描述

我正在使用 ggplot 创建一个 grob ggplotGrob,然后将其添加为复杂的 ggplot 构造中的背景层,因为在具有大型数据集annotation_custom的绘图中性能得到了很大改善。facet_wrap但是我无法将底层 grob 与 ggplot 正确对齐。

这个简单的示例显示了我要解决的问题。

library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg)) +
  geom_point(color = "red")
ggplot(mtcars, aes(wt, mpg)) +
  annotation_custom(grob = ggplotGrob(p)) +
  geom_point()

ggplotGrob 背景层

我希望带有红点的情节完全位于带有黑点的情节下方。

标签: rggplot2

解决方案


在将其添加为自定义注释之前,您可能只想抓取没有轴、边距等的面板。在下面的示例中,我将红点放大,以便您可以看到它们重叠。

library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg)) +
  geom_point(color = "red", size = 3)

grab_panel <- function(p) {
  gt <- ggplotGrob(p)
  layout <- gt$layout
  is_panel <- which(layout$name == "panel")[[1]]
  i <- layout$t[is_panel]
  j <- layout$l[is_panel]
  gt[i,j]
}

ggplot(mtcars, aes(wt, mpg)) +
  annotation_custom(grob = grab_panel(p)) +
  geom_point()

reprex 包于 2021-03-20 创建(v1.0.0)


推荐阅读