我真的很感謝您對以下問題的幫助。我知道幾種將單個繪圖保存到文件的方法。我的問題是:如何正確地將多字段保存到文件?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