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

A smart way to comment chunks of code in SAS

We all know there are two styles of comments in SAS: * ; and /* */. Normally when we want to disable a chunk of code, we will choose /* */.

But I bet you have such experience that you cannot do it well with /* */ since parts of the code itself might contain /* */ style comments. Therefore, in this case, only the code up to the first */ would be commented. So the best method to disable a chunk of code is to put it in a macro declaration and never call the macro, for example:

%macro comment;
---
---
---
%mend comment;