Extracting the legend grob from a plot or creating one manually

823 views
Skip to first unread message

Thomas

unread,
Jan 24, 2012, 7:32:57 AM1/24/12
to ggplot2
I am quite persistent in wanting to have additional colour scales,
when creating advanced plots. So far I have been able to overcome it
by manually creating layers for each new colour (not pretty, but it
works). The only thing that remains is to find a way to create legends
for the new scales.

I have in very old posts found a get_legends function described by
hadley but it does not seem to work with the more recent versions of
ggplot2. Furthermore he also described how to manually train a legend
grob:

colour <- scale_colour_hue("My scale")
colour$train(factor(c("a","b")))
grid.newpage()
grid.draw(gglegend(colour$legend_desc(), list(colour="point")))

but neither this seems to work on the newest version.

Is there any way to extract the legend grob in the newest ggplot2
versions?

Thanks as always

Thomas

Hadley Wickham

unread,
Feb 10, 2012, 7:58:19 AM2/10/12
to Thomas, ggplot2
> Is there any way to extract the legend grob in the newest ggplot2
> versions?

Probably, but I don't know off the top of my head, and it's likely to
break again in future versions. You may want to look into the code
for guide_legend in the development version to see how the guides are
generated.

Hadley

--
Assistant Professor / Dobelman Family Junior Chair
Department of Statistics / Rice University
http://had.co.nz/

baptiste auguie

unread,
Feb 10, 2012, 3:54:19 PM2/10/12
to Hadley Wickham, Thomas, ggplot2
Keeping in mind Hadley's reservations, try this:

p = qplot(mpg, wt, data=mtcars, colour=cyl);
g = ggplotGrob(p) ; gg = editGrob(getGrob(g, gPath("guide-box"),
grep=TRUE), vp=viewport()) ; grid.draw(gg)

HTH,

b.

> --
> You received this message because you are subscribed to the ggplot2 mailing list.
> Please provide a reproducible example: http://gist.github.com/270442
>
> To post: email ggp...@googlegroups.com
> To unsubscribe: email ggplot2+u...@googlegroups.com
> More options: http://groups.google.com/group/ggplot2

Thomas

unread,
Feb 16, 2012, 11:27:54 AM2/16/12
to ggplot2
Thanks that worked brilliant, though it is a bit slower than the
deprecated opts(keep='legend_box') due to the ggplotGrob call

best wishes Thomas


On 10 Feb., 21:54, baptiste auguie <baptiste.aug...@googlemail.com>
wrote:
> Keeping in mind Hadley's reservations, try this:
>
> p = qplot(mpg, wt, data=mtcars, colour=cyl);
> g = ggplotGrob(p) ; gg = editGrob(getGrob(g, gPath("guide-box"),
> grep=TRUE), vp=viewport()) ; grid.draw(gg)
>
> HTH,
>
> b.
>
> On 11 February 2012 01:58, Hadley Wickham <had...@rice.edu> wrote:
>
>
>
>
>
>
>
> >> Is there any way to extract the legendgrobin the newest ggplot2
Reply all
Reply to author
Forward
0 new messages