r - 将 grid.arrange() 绘图保存到文件

标签 r ggplot2 gridextra

我正在尝试使用ggplot2绘制多个图,并使用grid.arrange()排列它们。 由于我设法找到了描述我所遇到的确切问题的人,因此我引用了 link 中的问题描述。 :

当我在 grid.arrange() 之后使用 ggsave() 时,即

grid.arrange(sgcir1,sgcir2,sgcir3,ncol=2,nrow=2)
ggsave("sgcirNIR.jpg")

我不保存网格图,而是保存最后一个单独的 ggplot。有没有 实际保存由grid.arrange()显示的绘图的方法使用 ggsave() 或类似的东西? 除了使用旧方法

jpeg("sgcirNIR.jpg")
grid.arrange(sgcir1,sgcir2,sgcir3,ncol=2,nrow=2)
dev.off()

同一链接提供了以下解决方案:

require(grid)
require(gridExtra)
p <- arrangeGrob(qplot(1,1), textGrob("test"))
grid.draw(p) # interactive device
ggsave("saving.pdf", p) # need to specify what to save explicitly

但是,我不知道如何使用 ggsave() 来保存以下代码中 grid.arrange() 调用的输出,即取自link :

library(ggplot2)
library(gridExtra)
dsamp <- diamonds[sample(nrow(diamonds), 1000), ] 

p1 <- qplot(carat, price, data=dsamp, colour=clarity)
p2 <- qplot(carat, price, data=dsamp, colour=clarity, geom="path")

g_legend<-function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
return(legend)}

legend <- g_legend(p1)
lwidth <- sum(legend$width)

## using grid.arrange for convenience
## could also manually push viewports
grid.arrange(arrangeGrob(p1 + theme(legend.position="none"),
                                        p2 + theme(legend.position="none"),
                                        main ="this is a title",
                                        left = "This is my global Y-axis title"), legend, 
                     widths=unit.c(unit(1, "npc") - lwidth, lwidth), nrow=1)

# What code to put here to save output of grid.arrange()?

最佳答案

grid.arrange直接在设备上绘制。 arrangeGrob另一方面,不绘制任何内容,但返回一个 grob g ,您可以将其传递给 ggsave(file="whatever.pdf", g) .

它的工作方式与 ggplot 对象不同的原因是 ggplot2 无形地跟踪最新的绘图,我不认为 grid.arrange应该弄乱这个包私有(private)的计数器。

关于r - 将 grid.arrange() 绘图保存到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17059099/

相关文章:

r - geom_label 中的上标星

当应用于带有facet_wrap的箱线图时删除一个tableGrob

r - 将单独的图绘制在一起时自动调整轴限制

r - 在 ggplot2 的 facet-grid/facet_wrap 中调整面板的相对空间

r - R中使用ggplot函数的热图-如何对行进行聚类?

r - 修改 R 包数据

r - 从通过散点图拟合的回归线中排除异常值,而不从图中移除异常值

r - 如何在ggplot中将轴值强制为科学计数法

r - 做 arrangeGrob 时是否可以裁剪图?

r - 用于访问 ggplot2 图层中数据的点语法