extractLegend: Extract the legend from a ggplot

View source: R/extractLegend.R

extractLegendR Documentation

Extract the legend from a ggplot

Description

You often want this to share a legend between multiple plots that do not also share axes (i.e. you can't use faceting).

Usage

extractLegend(plot)

Arguments

plot

A plot made with ggplot.

Details

There is the (probably much better) ggpubr::ggarrange (not to be confused with egg::ggarrange) to use common legend for multiple plots. However, ggpubr depends on latest R version so it can give trouble. The code was taken from https://stackoverflow.com/questions/13649473/add-a-common-legend-for-combined-ggplots which has a ref to https://github.com/hadley/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs

Examples

## This example is not done yet. But it shows the idea
## Not run: 
mylegend <- extractLegend(p1)
p3 <- grid.arrange(arrangeGrob(p1 + theme(legend.position="none"),
                               p2 + theme(legend.position="none"),
                               nrow=1),
                               mylegend, nrow=2,heights=c(10, 1))

## End(Not run)

philipdelff/pmxtricks documentation built on Nov. 11, 2024, 5:16 p.m.