Skip to contents

Extracts the legend (guide-box) from a ggplot object as a grob that can be used independently with grid or cowplot.

Usage

get_legend(plot)

Arguments

plot

A ggplot object.

Value

A grob containing the legend, or NULL if the plot has no legend.

Details

This function is useful for cowplot workflows where you want to manually position a shared legend. The extracted legend can be combined with plots using cowplot::plot_grid() or drawn directly with grid::grid.draw().

Examples

library(ggplot2)

p <- ggplot(mtcars, aes(mpg, wt, color = factor(cyl))) +
  geom_point() +
  labs(color = "Cylinders")

# Extract the legend
leg <- get_legend(p)

# Draw just the legend
grid::grid.newpage()
grid::grid.draw(leg)