get_legend: Extract the legend of a ggplot2

View source: R/get_legend.R

get_legendR Documentation

Extract the legend of a ggplot2

Description

Extract the legend of a ggplot2

Usage

get_legend(p)

Arguments

p

a ggplot with a legend

Note

Could be combined with multiplot (see examples).

References

Adapted from http://stackoverflow.com/questions/12539348/ggplot-separate-legend-and-plot

See Also

https://github.com/hadley/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs

Examples

require(ggplot2)
p1 <- ggplot(iris) +
  aes(x = Sepal.Length, y = Sepal.Width, color = Species) +
  geom_point() +
  theme(legend.position = "bottom")
p2 <- ggplot(iris) +
  aes(x = Petal.Length, y = Petal.Width, color = Species) +
  geom_point()

# get legend from p1
l <- get_legend(p1)

# remove legends
p1 <- p1 + theme(legend.position = "none")
p2 <- p2 + theme(legend.position = "none")

# Combining
multiplot(p1, p2, l, heights = c(2, 2, 1))

larmarange/JLutils documentation built on March 24, 2023, 6:39 a.m.