Best way to add a footnote to a plot created with ggplot2

There are different kinds of tools for data visualization and ggplot2 is always my favorite. It is powerful, elegant and easy to use except for one minor defect — difficulty of adding footnote. Unlike adding title, it’s no explicit statement available to add a footnote directly. Let’s use the following plot as example (according to the mpg data set included in ggplot2).

library(ggplot2)
toyota <- mpg[which(mpg$manufacturer == 'toyota'), ]
p <- ggplot(toyota, aes(displ, hwy)) + facet_wrap(~ class, ncol = 2) + geom_point(aes(size=cyl))
print(p)

raw_plot

As you can see, I create a 4-panel scatter plot using displ as x-axis and hwy as y-axis. Let’s see how we can add the footnote to the plot.

Continue reading

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