15/02: subplots in ggplot2

Tags:
I make almost all my graphics in R using ggplot2. It is really excellent for exploratory analysis, because you can easily map variables to any aesthetic dimension of a plot. For instance, you can assign a variable to the size of points in a scatter plot, and another variable to the color, which gives the sort of nice balloon plots you see in National Geographic about the relative number and proportion of single women in New York or wherever.

Producing a specific plot layout for production graphics is a little bit troublesome. Ggplot uses the grid graphics package, which is somewhat complicated. There is some explanation of how to control plot layout in the ggplot manual, but it's useful to define the following two functions to provide MATLAB-like control over subplots.


subplot vplayout grid.newpage()
pushViewport(viewport(layout=grid.layout(y,x)))
}


To use these functions, call vplayout() to set up the plot grid, and then use the vp argument of the print() function to control which elements of the grid are actually used. For instance, the following code will plot to 3/4 of the horizontal space:


vplayout(4,1)
p print(p, vp=subplot(c(1,2,3),1))

Comments