g_legend: Extract ggplot legends

View source: R/legends.r

g_legendR Documentation

Extract ggplot legends

Description

Extracts the legend ('guide-box') from a ggplot2 object.

Usage

g_legend(a.gplot)

Arguments

a.gplot

ggplot2 or gtable object.

Details

The extraction is applied after the plot is trained and themes are applied. Modifying the legend is easiest by applying themes etc. to the ggplot2 object, before calling g_legend.

An alternative method for extracting the legend is using gtable::gtable_filter:

  gtable_filter(ggplotGrob(a.ggplot.obj), 'guide-box')

This method however returns a gtable object which encapsulates the entire legend. The legend itself may be a collection of gtable. We have only noticed a problem with this extra layer when using the returned legend with arrangeGrob (see examples).

Value

gtable (grob) object. Draw with grid.draw.

Author(s)

Baptiste AuguiƩ

See Also

grid_arrange_shared_legend, reposition_legend, gtable_filter

Examples

library(ggplot2)
library(gtable)
library(grid)
library(gridExtra)
library(gtable)
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
(d <- ggplot(dsamp, aes(carat, price)) +
 geom_point(aes(colour = clarity)) +
 theme(legend.position='bottom'))

legend <- g_legend(d)
grid.newpage()
grid.draw(legend)

(d2 <- ggplot(dsamp, aes(x=carat, fill=clarity)) +
  geom_histogram(binwidth=0.1) +
 theme(legend.position='bottom'))

grid.arrange(d  + theme(legend.position='hidden'),
             d2 + theme(legend.position='hidden'),
             bottom=legend$grobs[[1]])
# Above fails with more than one guide

legend2 <- gtable_filter(ggplotGrob(d), 'guide-box')
grid.arrange(d  + theme(legend.position='hidden'),
             d2 + theme(legend.position='hidden'),
             bottom=legend2$grobs[[1]]$grobs[[1]])
# Above fails with more than one guide



lemon documentation built on May 29, 2024, 8:48 a.m.