#' 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)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.