ggplot2: Two Or More Plots Sharing The Same Legend

2009 May 26
by learnr

Sometimes there is a need to combine two or more different plots that have a common legend. If these plots were placed in the same window, then one of the legends would be redundant.

This post shows how two ggplot2 plots can share the same legend. The solution was inspired by a thread on the ggplot2 mailinglist.

Let’s assume that we want to plot the following two relationships in the R’s built-in dataset mtcars, and use colour to display the cars with varying number of cylinders on the graph.:

a) Miles/(US) gallon – Gross horsepower – Number of cylinders

b) Weight (lb/1000) – Displacement (cu.in.) – Number of cylinders

Using qplot we first create the two plots, and make sure that the legends are not displayed by specifying opts(legend.position = "none"). Next we create a plot that displays only the legend, all the other elements of the plot are removed by opts(keep= "legend_box"). Finally, the two plots and the legend plot are placed onto a page with the help of grid.layout(), resulting in two plots with different axis sharing the same legend.

> library(ggplot2)
> p <- qplot(data = mtcars, mpg, hp, geom = "point",
     colour = cyl)
> p1 <- p + opts(legend.position = "none")
> p2 <- qplot(data = mtcars, wt, disp, geom = "point",
     colour = cyl) + opts(legend.position = "none")
> legend <- p + opts(keep = "legend_box")
> Layout <- grid.layout(nrow = 2, ncol = 2, widths = unit(c(2,
     0.4), c("null", "null")), heights = unit(c(1,
     1), c("null", "null")))
> vplayout <- function(...) {
     grid.newpage()
     pushViewport(viewport(layout = Layout))
 }
> subplot <- function(x, y) viewport(layout.pos.row = x,
     layout.pos.col = y)
> vplayout()
> print(p1, vp = subplot(1, 1))
> print(p2, vp = subplot(2, 1))
> print(legend, vp = subplot(1:2, 2))
http://learnr.files.wordpress.com/2009/05/sharedlegend.png
One Response leave one →
  1. 2009 September 3

    Thanks for this template! I built upon this post to make a 2D plot with histograms (or better: density plots) for each axis: http://blog.mckuhn.de/2009/09/learning-ggplot2-2d-plot-with.html

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS