我真的很感谢您对以下问题的帮助。我知道几种将单个绘图保存到文件的方法。我的问题是:如何正确地将多字段保存到文件?R - 将多槽保存到文件
首先,我不是经验丰富的R用户。我使用ggplot2来创建我的图,另外我应该提到的是我使用RStudio GUI。使用R Cookbook的example,我可以在一个窗口中创建多个图。
我想保存这个所谓的多槽到一个文件(最好是jpeg),但某种方式不能做到这一点。
我创建的multiplot如下:
##define multiplot function
multiplot <- function(..., plotlist=NULL, cols) {
require(grid)
# Make a list from the ... arguments and plotlist
plots <- c(list(...), plotlist)
numPlots = length(plots)
# Make the panel
plotCols = cols # Number of columns of plots
plotRows = ceiling(numPlots/plotCols) # Number of rows needed, calculated from # of cols
# Set up the page
grid.newpage()
pushViewport(viewport(layout = grid.layout(plotRows, plotCols)))
vplayout <- function(x, y)
viewport(layout.pos.row = x, layout.pos.col = y)
# Make each plot, in the correct location
for (i in 1:numPlots) {
curRow = ceiling(i/plotCols)
curCol = (i-1) %% plotCols + 1
print(plots[[i]], vp = vplayout(curRow, curCol))
}
}
## define subplots (short example here, I specified some more aesthetics in my script)
plot1a <- qplot(variable1,variable2,data=Mydataframe1)
plot1b <- qplot(variable1,variable3,data=Mydataframe1)
plot1c <- qplot(variable1,variable2,data=Mydataframe2)
plot1d <- qplot(variable1,variable3,data=Mydataframe2)
## plot in one frame
Myplot <- multiplot(plot1a,plot1b,plot1c,plot1d, cols=2)
这给了期望的结果。当我尝试保存到文件时出现问题。我可以在RStudio中手动执行此操作(使用导出 - >将绘图另存为图像),但我希望在脚本中运行所有内容。我设法只保存subplot1d(这是last_plot()),而不是完整的多槽。
我试过到目前为止:
使用ggsave
ggsave(filename = "D:/R/plots/Myplots.jpg")
这导致只有插曲1D被保存。
使用JPEG(),print()和dev.off()
jpeg(filename = "Myplot.jpg", pointsize =12, quality = 200, bg = "white", res = NA, restoreConsole = TRUE) print(Myplot) dev.off()
这导致在全白图像(只是我假设的背景)。 print(Myplot)返回NULL。
不知道我在做什么错在这里。我缺乏理解R是我坚持试图找到解决方案的原因。任何人都可以解释我做错了什么,也许建议一种方法来解决我的问题?
您也可以使用** gridExtra :: grid。排列(plot1a,plot1b,plot1c,plot1d,ncol = 2)** – dickoa 2012-07-30 12:32:11
gridExtra软件包不包含grid.arrange,它包含了似乎提供相同功能的arrangeGrob。我似乎还记得一个名为grid.arrange的函数,也许作者更改了包中的函数标题。 – 2012-07-30 15:22:51
'grid.arrange'应该在gridExtra中。可以肯定的是,'arrangeGrob' vs'multiplot'的好处之一是它与'ggsave'兼容,并且可以存储复合grob供以后使用。 – baptiste 2012-07-30 20:26:06