gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 11:33:40 24 4
gpt4 key购买 nike

我正在尝试将两个图形对象 ( 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com