Why isn't `g_legend` part of the ggplot2 package?

25 views
Skip to first unread message

Stefan Høj-Edwards

unread,
Apr 20, 2017, 5:32:19 AM4/20/17
to ggplot2
The function `g_legend` extracts the grob of the guidebox (legend). It is extremely useful when e.g. combining multiple plots with same legend.

The code is "straight forward", and I have found the same code multiple places on, most commonly stackoverflow. It is quite simply:

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)
}

It seems to me this function is quite useful and should be part of the ggplot2 package. Perhaps as an alternative, gridExtra or gtable. But it requries the hard-coded name 'guide-box', perhaps ggplot2 is most fitting in case it gets changed?

I will gladly add it to the relevant package with necessary documentation, if there is any interest.

/Stefan

Wouter van der Bijl

unread,
Apr 20, 2017, 5:56:32 AM4/20/17
to ggplot2
See perhaps cowplot::get_legend ?

W.
Reply all
Reply to author
Forward
0 new messages