List of plot into single pdf in R

Viewed 441

i'm trying to export a list of ggplot item into a single .pdf. I've been looking for tips here in SO, but ALL the solutions found didn't worked for me. All i can get are outputs with .pdf that cannot be opened, or results with no pages.

Could anyone give me advice on this?

here is my code example:

p <- lapply(x, fun)
#and i tried
    library(gridExtra)

pdf("plots.pdf", onefile = TRUE)
for (i in seq(length(p))) {
  do.call("grid.arrange", p[[i]])  
}
dev.off()

#and this


 GG_save_pdf = function(list, filename) {


    #start pdf

  pdf(filename)

      #loop
      for (p in list) {
        print(p)
      }

      #end pdf
      dev.off()

      invisible(NULL)
    }
    #and this too
library(ggplot2)


pdf("allplots.pdf",onefile = TRUE)
for(i in glist){
   tplot <- ggplot(df, aes(x = as.factor(class), y = value))
   print(tplot)
}
dev.off()

Can anyone give me guidance? I think it's not a problem of code itself, rather my understanding on what is going on with the code.

1 Answers

You were close. Since your p is a list, do.call suffices to apply "grid.arrange" on a list, no loop etc. needed. Example:

library(ggplot2)

## create three example plots
p <- replicate(3, ggplot(mtcars, aes(hp, mpg)) +
  geom_point(), simplify=F)

str(p, 1)
# List of 3
#  $ :List of 9
#   ..- attr(*, "class")= chr [1:2] "gg" "ggplot"
#  $ :List of 9
#   ..- attr(*, "class")= chr [1:2] "gg" "ggplot"
#  $ :List of 9
#   ..- attr(*, "class")= chr [1:2] "gg" "ggplot"


library(gridExtra)

pdf("plots.pdf", onefile = TRUE)
do.call("grid.arrange", p)  
dev.off()

Resulting .pdf:

enter image description here

Related