Skip to content

Share a legend between two ggplot2 graphs

johnDorian edited this page Jul 6, 2012 · 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.
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]]
return(legend)}

legend<-g_legend(p1)


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

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

Clone this wiki locally