R/get_legend.R

Defines functions get_legend

Documented in get_legend

#' Extract legend from a ggplot
#'
#' 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.
#'
#'@export
#'
#'@param myggplot A plot built with \code{ggplot}
#'@return The legend of the plot, as an object
#'@examples
#'## 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))


get_legend<-function(myggplot){
  tmp <- ggplot_gtable(ggplot_build(myggplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  return(legend)
}
victoria-ramirez/expanded_slf documentation built on July 1, 2020, 12:15 a.m.