57

I know that

 pdf("myOut.pdf")

will print to a PDF in R. What if I want to

  1. Make a loop that prints subsequent graphs on new pages of a PDF file (appending to the end)?

  2. Make a loop that prints subsequent graphs to new PDF files (one graph per file)?

Dan Goldstein
  • 24,229
  • 18
  • 37
  • 41

3 Answers3

64

Did you look at help(pdf) ?

Usage:

 pdf(file = ifelse(onefile, "Rplots.pdf", "Rplot%03d.pdf"),
     width, height, onefile, family, title, fonts, version,
     paper, encoding, bg, fg, pointsize, pagecentre, colormodel,
     useDingbats, useKerning)

Arguments:

file: a character string giving the name of the file. For use with
      'onefile=FALSE' give a C integer format such as
      '"Rplot%03d.pdf"' (the default in that case). (See
      'postscript' for further details.)

For 1), you keep onefile at the default value of TRUE. Several plots go into the same file.

For 2), you set onefile to FALSE and choose a filename with the C integer format and R will create a set of files.

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
  • 8
    How do you move to the next PDF page if you are using grid layouts? For example you prepare a few ggplots, put them into viewports on p1 of the multi-page PDF, but how do you get the next viewport to go onto page 2 ... 3 .... etc? – Thomas Browne Nov 24 '14 at 16:50
43

Not sure I understand.

Appending to same file (one plot per page):

pdf("myOut.pdf")
for (i in 1:10){
  plot(...)
}
dev.off()

New file for each loop:

for (i in 1:10){
  pdf(paste("myOut",i,".pdf",sep=""))
  plot(...)
  dev.off()
}
Mark
  • 106,305
  • 20
  • 172
  • 230
  • 5
    You don't even need the paste() over filenames -- R can do that for you too; see my answer. – Dirk Eddelbuettel Sep 08 '09 at 18:12
  • How could you include several plots in each page? For example 5 plots in one page, and the next 5 plots in the next page. I have tried including `par(mfrow=c(5,1))` before the command `plot`, but I have only got that each plot (in this case 10 plots) appears in 10 pages but with the size of the dimensions defined in the function `par`, in this case 5 rows and 1 column. Thanks in advance – Ruben Apr 27 '16 at 16:40
  • 1
    @Ruben. You should call pdf() before par(mfrow=c(5,1)) (that is: NOT in the opposite direction). You also might consider increasing the width and height in pdf() margins are to small. Hope this helps. – user3375672 Sep 13 '17 at 16:51
1
pdf(file = "Location_where_you_want_the_file/name_of_file.pdf", title="if you want any")
plot() # Or other graphics you want to have printed in your pdf
dev.off()

You can plot as many things as you want in the pdf, the plots will be added to the pdf in different pages. dev.off() closes the connection to the file and the pdf will be created and you will se something like

> dev.off()
null device 1