Share a legend between two ggplot2 graphs - brodieG/ggplot2 GitHub Wiki

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.
library(ggplot2)
library(gridExtra)
dsamp <- diamonds[sample(nrow(diamonds), 1000), ] 

p1 <- qplot(carat, price, data=dsamp, colour=clarity)
p2 <- qplot(carat, price, data=dsamp, colour=clarity, geom="path")

g_legend<-function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[leg](/brodieG/ggplot2/wiki/leg)
return(legend)}

legend <- g_legend(p1)
lwidth <- sum(legend$width)

## using grid.arrange for convenience
## could also manually push viewports
grid.arrange(arrangeGrob(p1 + theme(legend.position="none"),
                                        p2 + theme(legend.position="none"),
                                        main ="this is a title",
                                        left = "This is my global Y-axis title"), legend, 
                     widths=unit.c(unit(1, "npc") - lwidth, lwidth), nrow=1)