Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save multiple graphs one after another in one pdf file [duplicate]

Tags:

plot

r

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  
}  
like image 878
user961932 Avatar asked Sep 23 '11 20:09

user961932


People also ask

How to save multiple plots in PDF in R?

Save Multiple Plots to Same Page in PDF: To save multiple plots to the same page in the PDF file, we use the par() function to create a grid and then add plots to the grid. In this way, all the plots are saved on the same page of the pdf file. We use the mfrow argument to the par() function to create the desired grid.

How to save plots in R?

Under Windows, right click inside the graph window, and choose either "Save as metafile ..." or "Save as postscript ..." If using Word, make sure to save as a metafile.

What does the par function do in R?

The par() function is used to set or query graphical parameters. We can divide the frame into the desired grid, add a margin to the plot or change the background color of the frame by using the par() function. We can use the par() function in R to create multiple plots at once.


1 Answers

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.

like image 155
Mark Avatar answered Sep 25 '22 13:09

Mark