get_legend: Extract legend from a ggplot

Description Usage Arguments Value Examples

View source: R/get_legend.R

Description

The function takes a grob object and extracts the legend. Useful when making panels of figures and needing a shared legend to be displayed only once.

Usage

1
get_legend(myggplot)

Arguments

myggplot

A plot built with ggplot

Value

The legend of the plot, as an object

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
## Examples
d1 <- tibble(x = runif(100, 0, 15),
            y = x + rnorm(100, sd = 1),
            z = sample(c("A", "B", "C"), 100, replace = T))
d2 <- tibble(x = runif(100, -10, 10),
            y = - x^2 + rnorm(100, sd = 1),
            z = sample(c("A", "B", "C"), 100, replace = T))
g1 <- ggplot(d1) +
  geom_point(aes(x = x, y = y, col = z))
g2 <- ggplot(d2) +
  geom_point(aes(x = x, y = y, col = z))
g_legend <- get_legend(g1)
grid.arrange(g1 + theme(legend.position = "none"),
             g2 + theme(legend.position = "none"),
             g_legend, nrow = 1,
             widths = c(3,3,1))

victoria-ramirez/expanded_slf documentation built on July 1, 2020, 12:15 a.m.