Pages

Arrange multiple ggplot2 plots in the same image window

In a previous tutorial I showed you how to create plots faceted by the level of a third variable using ggplot2. A commenter asked about using faceted plots and viewports and reminded me of this function I found in the ggplot2 Google group. The arrange function below is similar to using par(mfrow=c(r,c)) in base graphics to put more than one plot in the same image window.



The basic idea is that you assign ggplot2 plots to an object, and then use the arrange function to display two or more. Here's an example. First copy and paste the code above (or put in your Rprofile). Next install and/or load ggplot2 as described in a previous ggplot2 tutorial.

# Load the diamonds dataset
data(diamonds)

# Create a histogram, assign to "plot1"
plot1 <- qplot(price,data=diamonds,binwidth=1000)

# Create a scatterplot
plot2 <- qplot(carat,price,data=diamonds)

# Arrange and display the plots into a 2x1 grid
arrange_ggplot2(plot1,plot2,ncol=1)
And here's what you should get:


...