16

Possible Duplicate:
How to print R graphics to multiple pages of a PDF and multiple PDFs?

I am new to R and have a quick question. The following code writes one .pdf file for each graph. I would like to add figures one after another in ONE pdf file. Thank you so much. Greatly appreciate any help.

i=5  
while (i<=10)   
{   
  name1="C:\\temp\\"  
  num=i   
  ext = ".pdf"  
  path3 = paste(name1,num,ext)  
  par(mfrow = c(2,1))  
  pdf(file=path3)  
  VAR1=rnorm(i)  
  VAR2=rnorm(i)  
  plot(VAR1,VAR2)  
  dev.off()  
  i=i+1  
}  
Community
  • 1
  • 1
user961932
  • 369
  • 2
  • 5
  • 8

1 Answers1

32

Just move your pdf() function call and your dev.off() call outside the loop:

somePDFPath = "C:\\temp\\some.pdf"
pdf(file=somePDFPath)  

for (i in seq(5,10))   
{   
  par(mfrow = c(2,1))
  VAR1=rnorm(i)  
  VAR2=rnorm(i)  
  plot(VAR1,VAR2)   
} 
dev.off() 

Note my use the the seq() function to loop instead of while() with a counter variable.

Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
Mark
  • 106,305
  • 20
  • 172
  • 230
  • I tired this, but it does not save the file. – user2806363 Aug 11 '14 at 20:13
  • 1
    @user2806363, I just tried the above snippet in R 3.1.1 and it works exactly the same as it did 3 years ago. My guess is your file path is invalid for your setup... – Mark Aug 11 '14 at 20:22
  • Yes, it works.for my case I have to save aroud 10000 plots in one pdf file. how can I put more than one plot in one page instead of puting one plot per page? I don't want to have .pdf file with 10000 pages. I like to have .pdf file around 2000 pages. – user2806363 Aug 11 '14 at 20:26
  • 2
    @user2806363, look at the help for `par`, in particular the `mfrow` option. `pdf(file=somePath); par(mfrow=c(2,2)); plot(x); plot(y); plot(z); plot(q); dev.off()`, this would create one page with the plots arranged 2x2... – Mark Aug 11 '14 at 22:09
  • This works fine for me. Thank you Mark, it was simple and just what I needed. – Austin Oct 22 '18 at 20:12
  • However, it is not generalizable for automated plots of model results, that partition the screen as they want (usually 2x2) and produce >4 plots – Gmichael Apr 09 '21 at 09:47