合并两个 grobs ,其中一个使用 grid.draw 创建

Combining two grobs , one of them created using grid.draw

我正在尝试将两个图形对象 (grob) 组合成一个图 - 其中一个是使用 "standard ggplot()" 调用创建的,另一个是在 [=15] 上使用 grid.draw() =] 对象 ().

library(ggplot2)
library(grid)
library(gridExtra)

plot_gtable <- function(x) {
  grid::grid.draw(ggplot_gtable(ggplot_build(x)))
}

plot1 <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
plot2 <- plot_gtable(ggplot(mtcars, aes(mpg)) + geom_dotplot())

grid.arrange(plot1, plot2)

Error in gList(structure(list(wrapvp = structure(list(x = structure(0.5, class = "unit", valid.unit = 0L, unit = "npc"), : only 'grobs' allowed in "gList"

reprex package (v0.2.1)

创建于 2018-12-12

显然,调用 grid.draw 会产生 NULL 对象,而不是 grob,这似乎是 grid.arrange() 在这种情况下失败的原因。

我尝试先调用和不调用 grid::grid.newpage

我尝试使用 grid::viewportgridExtra::arrangeGrobggpubr::ggarrangecowplot::plot_grid 以及 patchwork 包,但都无济于事。

如何创建包含这些对象的组合图?

当使用 grid.arrange 组合绘图 and/or grobs 时,您希望使用实际对象而不是尝试绘制它。这就是为什么 plot2NULL 的原因,因为它是绘制的而不是返回的,因此不能合并。所以在组合地块之前不要画它。[=​​14=]

library(ggplot2)
library(gridExtra)

# example ggplot
plot1 <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
# example gtable
plot2 <- ggplotGrob(plot1)

grid.arrange(plot1, plot2)