g_legend: Extract legend from ggplot geom object

Description Usage Arguments Details Value References Examples

Description

Lets you extract a ggplot legend to be used elsewhere.

Usage

1
g_legend(gg.plot)

Arguments

gg.plot

A ggplot object

Details

A function to extract the legend from a ggplot object

This function pulls out the legend as a grob object from a ggplot object. This lets you play around with a plots layout by using the arrangeGrob function.

Value

The legend as a grob object from the plot

References

Obtained from http://stackoverflow.com/questions/11883844

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
## Create a plot with a legend
library(ggplot2)
plt1 <- ggplot() + geom_boxplot(aes(factor(gear), mpg, fill=factor(gear)), mtcars)
## Extract the legend from the plot.
plt_legend <- g_legend(plt1)
## Create a second boxplot with the same fill
plt2 <- ggplot() + geom_boxplot(aes(factor(gear), disp, fill=factor(gear)), mtcars)
## Suppress the legends from both plots
plt1 <- plt1 +  theme(legend.position="none")
plt2 <- plt2 +  theme(legend.position="none")
library(gridExtra)
combined_plot <- arrangeGrob(plt1, plt2, plt_legend, ncol=3)
combined_plot
## Or a slightly nicer example
combined_plot <- arrangeGrob(arrangeGrob(plt1, plt2, ncol=1), plt_legend, ncol=2, widths=c(0.8,0.2))
combined_plot

johnDorian/ggsnippets documentation built on May 19, 2019, 3:02 p.m.