Skip to content

Share a legend between two ggplot2 graphs

baptiste edited this page Sep 2, 2010 · 11 revisions

Share a legend between two ggplot2 graphs

Goal: align two plots, and place one or two legends on the side.

It is sometimes possible to obtain good results by creating a dummy facetting of the data as in Align-two-plots-on-a-page. For greater control, you can also use Grid to place the plots and the legends in an arbitrary layout,

Idea:

  1. create your two plots p1 and p2
  2. save the legend of p1 as a separate grob,
  3. strip the legend of p1 and p2,
  4. create three viewports on the page and print p1, p2, p3.
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
d <- qplot(carat, price, data = dsamp, colour = clarity)
 
p3 <- d + opts(keep = "legend_box")
 
p1 <- d + opts(legend.position = "none")
p2 <- d + opts(legend.position = "none")
 
p3
 
pushViewport(viewport(x = 0.4,y = 0.75, width = 0.8, height = 0.5,
    angle = 0, name = "topleftvp"))
grid.rect()
print(p1, vp = "topleftvp")
upViewport()
pushViewport(viewport(x = 0.4,y = 0.25, width = 0.8, height = 0.5,
    angle = 0, name = "botleftvp"))
grid.rect()
print(p2, vp = "botleftvp")
upViewport()

Note: The ggplot2 wiki is no longer maintained, please use the ggplot2 website instead!

Clone this wiki locally