Skip to contents

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.

Usage

get_legend(plot, position = NULL)

Arguments

plot

A plot object.

position

Optional legend position to extract. One of "left", "right", "top", "bottom", or "inside". Default is NULL, which returns the first non-empty legend grob.

Value

The legend grob, or NULL if the plot has no legend.

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]