Extracts the legend (guide-box) from a ggplot object as a grob that can be used independently with grid or cowplot.
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)