我正在尝试使用ggplot2
绘制多个绘图,并使用grid.arrange()
对它们进行排列。由于我设法找到了描述我所遇到的确切问题的人,我引用了来自link的问题描述
当我在grid.arrange()
之后使用ggsave()
时,即
grid.arrange(sgcir1,sgcir2,sgcir3,ncol=2,nrow=2) ggsave("sgcirNIR.jpg")
我没有保存网格图,而是保存了最后一个单独的ggplot。有没有什么方法可以使用ggsave()
或类似的东西来保存grid.arrange()
显示的绘图?而不是使用旧的方法
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()?
发布于 2013-06-13 05:07:31
grid.arrange
直接在设备上绘制。另一方面,arrangeGrob
不会绘制任何东西,只会返回一个grob g
,您可以将其传递给ggsave(file="whatever.pdf", g)
。
它与grid.arrange
对象的工作方式不同的原因是,如果没有指定,ggplot2会以不可见的方式跟踪最新的绘图,并且我认为ggplot不应该将这个计数器弄乱到包的私有位置。
发布于 2015-01-25 20:03:34
我对babptiste的提议有一些问题,但最终还是得到了它。下面是您应该使用的内容:
# draw your plots
plot1 <- ggplot(...) # this specifies your first plot
plot2 <- ggplot(...) # this specifies your second plot
plot3 <- ggplot(...) # this specifies your third plot
#merge all three plots within one grid (and visualize this)
grid.arrange(plot1, plot2, plot3, nrow=3) #arranges plots within grid
#save
g <- arrangeGrob(plot1, plot2, plot3, nrow=3) #generates g
ggsave(file="whatever.pdf", g) #saves g
这应该可以很好地工作。
发布于 2015-08-18 15:08:36
另一种将grid.arrange保存为pdf文件的简单方法是使用pdf():
pdf("filename.pdf", width = 8, height = 12) # Open a new pdf file
grid.arrange(plot1, plot2, plot3, nrow=3) # Write the grid.arrange in the file
dev.off() # Close the file
它允许在排列中合并除ggplot之外的其他内容,如表格……
https://stackoverflow.com/questions/17059099
复制相似问题