ggplot2 plotting over multiple pages

I bet you have done this before: tying to use ggplot to create graphs over multiple pages.  The first thing I thought about this question is wrapping the ggplot code all up in a for loop like below, in between the pdf() and dev.off() functions. For example:

pdf(filename)
for (i in seq){ 
 ...
 ...
 ggplot(...) + geom_point(...) 
}
dev.off()

However, if you try to run this code, you will find that the for loop doesn’t seem to wait for ggplot to do its thing, and blazes through its loop very quickly and outputs an invalid PDF.

If you run pdf() first, then set i=1, run the above code inside the for loop, then set i=2, until finish the loop then turn off the device, the resulting PDF looks great.

So what’s really going on?

The answer is on Page 39 of the ggplot2 book. It tells us that when you create ggplot2 objects, you can “Render it on screen, with print(). This happens automatically when running interactively, but inside a loop or function, you’ll need to print() it yourself”. So the code below works.

pdf(filename) 
for (i in seq){ 
 ...
 ...
 p <- ggplot(...) + geom_point(...) 
 print(p)
} 
dev.off()

 

Reference:

http://stackoverflow.com/questions/3398568/r-ggplot-plotting-over-multiple-pages