我正在尝试将两个图形对象 ( grob
) 组合成一个图 - 其中一个使用“标准 ggplot()
”调用创建,另一个使用 grid.draw()
创建在 ggplot_gtable
上对象 ( based on this thread )。
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 创建于 2018-12-12 (v0.2.1)
显然,调用 grid.draw
结果 NULL
对象,不是 grob
,这似乎是为什么 grid.arrange()
的原因在这种情况下失败。
我尝试过调用和不调用 grid::grid.newpage
第一的。
我尝试使用 grid::viewport
和 gridExtra::arrangeGrob
和 ggpubr::ggarrange
和 cowplot::plot_grid
还有patchwork
包裹,一切都无济于事。
如何使用这些对象创建组合图?
最佳答案
当使用 grid.arrange
组合绘图和/或 grob 时,您希望使用实际对象而不是尝试绘制它。这就是为什么 plot2
是 NULL
的原因,因为它是绘制的而不是返回的,因此不能组合。所以在组合地 block 之前不要画它。
library(ggplot2)
library(gridExtra)
# example ggplot
plot1 <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
# example gtable
plot2 <- ggplotGrob(plot1)
grid.arrange(plot1, plot2)
关于r - 组合两个 grobs ,其中一个是使用 grid.draw 创建的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53742970/