g_legend: Extract ggplot legends

Description Usage Arguments Details Value Author(s) See Also Examples

View source: R/legends.r

Description

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

Usage

1
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:

1
  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 grid.arrange (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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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 July 1, 2018, 9:02 a.m.