Description Usage Arguments Details Value References Examples
Lets you extract a ggplot legend to be used elsewhere.
1 | g_legend(gg.plot)
|
gg.plot |
A ggplot object |
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.
The legend as a grob object from the plot
Obtained from http://stackoverflow.com/questions/11883844
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
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.