首页 > 解决方案 > 结合两个 grobs ,其中一个使用 grid.draw 创建

问题描述

我正在尝试grobggplot()两个图形对象(grid.draw()ggplot_gtable

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)

gList(structure(list(wrapvp = structure(list(x = structure(0.5, class = "unit", valid.unit = 0L, unit = "npc")) 中的错误,: "gList" 中只允许“grobs”

reprex 包(v0.2.1)于 2018 年 12 月 12 日创建

显然,调用grid.draw结果是NULLobject 而不是 a ,这似乎是在这种情况下失败grob的原因。grid.arrange()

我尝试了先打电话和不打电话grid::grid.newpage

我尝试使用grid::viewportand gridExtra::arrangeGroband ggpubr::ggarrangeand cowplot::plot_gridand alsopatchwork包,都无济于事。

如何使用这些对象创建组合图?

标签: rggplot2gridviewvisualizationgrob

解决方案


grid.arrange当使用你想要使用实际对象而不是试图绘制它来组合绘图和/或 grobs时。这就是为什么plot2NULL被绘制而不是返回,因此不能组合。所以在组合情节之前不要绘制它。

library(ggplot2)
library(gridExtra)

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

grid.arrange(plot1, plot2)

推荐阅读