Learn R Programming

ggguides (version 1.1.4)

get_legend: Extract Legend from a ggplot

Description

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)

Value

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

Arguments

plot

A ggplot object.

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().

See Also

shared_legend, collect_legends

Examples

Run this code
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)

Run the code above in your browser using DataLab