get_legend: Retrieve the legend of a plot

Description Usage Arguments Value Examples

View source: R/get_legend.R

Description

This function extracts just the legend from a ggplot

Usage

1

Arguments

plot

A ggplot or gtable from which to retrieve the legend

Value

A gtable object holding just the lengend

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
p1 <- ggplot(mtcars, aes(mpg, disp)) + geom_line()
plot.mpg <- ggplot(mpg, aes(x = cty, y = hwy, colour = factor(cyl))) + geom_point(size=2.5)
# Note that these cannot be aligned vertically due to the legend in the plot.mpg
ggdraw(plot_grid(p1, plot.mpg, ncol=1, align='v'))

legend <- get_legend(plot.mpg)
plot.mpg <- plot.mpg + theme(legend.position='none')
# Now plots are aligned vertically with the legend to the right
ggdraw(plot_grid(plot_grid(p1, plot.mpg, ncol=1, align='v'),
                 plot_grid(NULL, legend, ncol=1),
                 rel_widths=c(1, 0.2)))

Example output

Loading required package: ggplot2

Attaching package: 'cowplot'

The following object is masked from 'package:ggplot2':

    ggsave

Warning message:
In align_plots(plotlist = plots, align = align) :
  Graphs cannot be vertically aligned. Placing graphs unaligned.

cowplot documentation built on July 30, 2017, 9 a.m.