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