r - 组合两个 grobs ,其中一个是使用 grid.draw 创建的

标签 r ggplot2 gridview visualization grob

我正在尝试将两个图形对象 ( 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::viewportgridExtra::arrangeGrobggpubr::ggarrangecowplot::plot_grid还有patchwork包裹,一切都无济于事。

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

最佳答案

当使用 grid.arrange 组合绘图和/或 grob 时,您希望使用实际对象而不是尝试绘制它。这就是为什么 plot2NULL 的原因,因为它是绘制的而不是返回的,因此不能组合。所以在组合地 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/

相关文章:

r - 在 R 中使用 dplyr 过滤时,为什么过滤掉的变量级别仍保留在过滤数据中?

r - ggplot : how to get legend linetype group-dependent while errorbar linetype solid

r - 将 yaxis 传奇保存为单独的 grob?

r - 带填充和组的 ggplot2

r - 如何在R中的tableGrob输出表中合并垂直单元格?

flutter - 如何计算Flutter GridView子级的默认高度和宽度?

r - R 中的 SAS 宏变量

r - 在此示例中, "collapsing to unique ' x' values"是什么意思?

c# - 如何通过编程方式将货币格式添加到 AspxPivotGrid 中的数据行?

css - 在 GridView 中使用“编辑命令列”按钮时,获取要更改的选定行背景颜色