8

I have at least 10 plots by ggplot(we can call them plot1, plot2 ....). I can output them into separate pdf files. But I prefer to output them in only one pdf file but several pages. One page, one plot from ggplot.

I tried to list all plots and use ggsave but it can not work. Any idea or script can help? Thank you

cutebunny
  • 769
  • 2
  • 9
  • 21

2 Answers2

15

See the pdf function for this.

For three plots it would look like this (saving into your working directory with default naming). Run through dev.off line before you can open file.

pdf()
plot1
plot2
plot3
dev.off()

If your plots are already stored in a list named list1:

pdf()
list1
dev.off()
aosmith
  • 34,856
  • 9
  • 84
  • 118
  • Thank you! I tried both. This first one can work. The second one can not. – cutebunny Jun 25 '15 at 14:23
  • @cutebunny I actually use the second version much more often than the first when I have lots of plots I want to make and peruse. See, e.g., [this](http://stackoverflow.com/a/19147917/2461552). – aosmith Jun 25 '15 at 14:36
6

Based on aosmith's answer, here's a simple wrapper function to save lists of ggplot2 plots to a single pdf.

GG_save_pdf = function(list, filename) {
  #start pdf
  pdf(filename)

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

  #end pdf
  dev.off()

  invisible(NULL)
}
CoderGuy123
  • 6,219
  • 5
  • 59
  • 89