[R] ggplot legend consolidation

hadley wickham h.wickham at gmail.com
Mon Sep 10 16:58:18 CEST 2007


> I have recently been introduced to the ggplot package by Hadley Wickham
> and must say I am quite impressed so far at how easy it is to make
> attractive plots, but one thing I am struggling over is how to
> consolidate legends.

It's not currently possible to consolidate them (although in the
distant future that would be something nice to have), but you can turn
them off:

hide_colour <- scale_colour_continuous()
hide_colour$legend <- FALSE

p <- ggplot(data = mtcars) +
  geom_point(mapping = aes(x = hp, y = mpg, colour = cyl)) +
  hide_colour

You'll also need to twiddle your viewports a little so that you still
have space for the viewport, since space will not be allocated
automatically anymore.

The next thing is to extract the grob for the legend itself - this is
a little tricker, because there's currently no way to get at the
scales after they have been "trained" with the
data.  Load get_legends from http://pastie.textmate.org/95755, and
then you can do:

grid.newpage(); grid.draw(get_legends(p))

If you're not familiar enough with grid to stitch all of these pieces
together, please let me know, but this should be enough to get you
started.

Hadley



More information about the R-help mailing list