2017-09-27 39 views
0

我已檢查此鏈接中列出的解決方案: Saving grid.arrange() plot to file 但無法將其應用於我的問題,解決方案不明確。在迴路中保存grid.arrange輸出並打印到文字(ReporteRs)或PDF文件

我有一個循環其產生四個圖對於每個i,然後將其設置在grid.arrange:

for (i in 1:n)){ 
p1<- ggplot(predictors, aes(x = x1, y = x2)) + geom_point() 
p2<- ggplot(temp) + geom_histogram(aes(x=value)) + 
    facet_grid(. ~ variable, scales = "free_x") 
p3<- ggplot(predictors_trans) + geom_point(aes(x = trans.x1, y = trans.x2)) 
p4<- ggplot(temp) + geom_histogram(aes(x=value), data = temp) + 
    facet_grid(. ~ variable, scales = "free_x") 

###arrange plots in grid: 
plot_list[[i]] = (grid.arrange(p1, p2, p3, p4)) 

###write grid to doc via ReporteRs package 
mydoc2 = addPlot(doc = mydoc2, fun = print, x = plot_list[[i]], 
    vector.graphic = TRUE, par.properties = parCenter(), width = 6, heigth = 

###save all images to directory as well 
ggsave(filename=paste("myplot",i,".jpg",sep=""), plot_list[[i]]) 

    } 

的曲線中產生和保存,但是之後它產生的字文檔是空MYDOC2被寫入到它:

writeDoc(mydoc2, "why224.docx") 
browseURL("why224.docx") 

我也試着寫只是圖像到PDF,果然空:

pdf("plots61.pdf") 
for (i in 1:n) { 
      print((plot_list[[i]])) 
      } 
dev.off() 

如果我刪除x=plot_list[[i]]並在addPlot命令設置x=grid.arrange(p1,p2,p3,p4),我得到一個word文檔裏面的空白影像:

enter image description here 沒有人有任何解決方案如何打印grid.arrange對象或一個ggsave結果循環到文檔(word或pdf)?謝謝。

回答

1

With ggsave use arrangeGrob。這個循環可以節省網格提供了單獨的PDF每次迭代:

library(ggplot2) 
library(gridExtra) 
for(i in 1:4) { 
    p1 <- qplot(1, 1, geom = "point") 
    p2 <- qplot(1, 1, geom = "point") 
    p3 <- qplot(1, 1, geom = "point") 
    p4 <- qplot(1, 1, geom = "point") 
    g <- arrangeGrob(p1, p2, p3, p4) 
    ggsave(file = paste0("myplot", i, ".pdf"), g) 
} 
+0

非常感謝,你知道如何將所有地塊從循環的每次迭代保存到一個PDF或最好word文檔? –

+0

我的解決方案不是將它們保存爲pdf嗎?我不明白你的意思。 – PoGibas

+0

嗨是的,這確實保存爲PDF格式,但保存每個相應的PDF,有沒有辦法將所有的循環輸出保存爲一個PDF? –