Extract the legend grob from a plot object. ggplot2 3.5+ places legends in
guide-box-left / right / top / bottom / inside slots; unused slots
are empty zeroGrobs. This helper returns the first non-empty legend, or
the legend at position when that argument is set.
Examples
library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg, colour = factor(cyl))) +
geom_point()
get_legend(p)
#> TableGrob (5 x 5) "guide-box": 2 grobs
#> z cells name grob
#> 1 1 (3-3,3-3) guides gtable[layout]
#> 2 0 (2-4,2-4) legend.box.background zeroGrob[NULL]
get_legend(p + theme(legend.position = "bottom"), position = "bottom")
#> TableGrob (5 x 5) "guide-box": 2 grobs
#> z cells name grob
#> 1 1 (3-3,3-3) guides gtable[layout]
#> 2 0 (2-4,2-4) legend.box.background zeroGrob[NULL]