2

I have checked the solution listed in this link: Saving grid.arrange() plot to file but cannot apply it to my problem, the solution is not clear.

I have a loop which creates four plots for each i, which are then arranged in a 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]])

     }

the plots are generated and saved, and but the word document generated is empty after it mydoc2 is written to it:

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

I also tried writing just the images to a PDF, which turns out empty:

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

if I remove x=plot_list[[i]] and set x=grid.arrange(p1,p2,p3,p4) in the addPlot command, I get a word document with a blank image inside:

enter image description here Does anyone have any solutions as to how to print grid.arrange object or ggsave results of a loop to a document (word or pdf)? thanks.

pogibas
  • 27,303
  • 19
  • 84
  • 117
El_1988
  • 339
  • 3
  • 13

1 Answers1

3

With ggsave use arrangeGrob. This loop saves grids to a separate pdf for each iteration:

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)
}
pogibas
  • 27,303
  • 19
  • 84
  • 117
  • Thanks alot, do you know how to save all plots from each iteration of the loop to one PDF or preferably word document? – El_1988 Sep 27 '17 at 16:30
  • Doesn't my solution save them into a pdf? I don't get what you mean. – pogibas Sep 27 '17 at 18:45
  • Hi yes this does save to pdf but saves each to a corresponding pdf, is there a way to save all of the loop outputs to one pdf? – El_1988 Sep 28 '17 at 12:05