grid_arrange_shared_legend: Share a legend between multiple plots

View source: R/legends.r

grid_arrange_shared_legendR Documentation

Share a legend between multiple plots

Description

Extract legend, combines plots using arrangeGrob / grid.arrange, and places legend in a margin.

Usage

grid_arrange_shared_legend(
  ...,
  ncol = length(list(...)),
  nrow = 1,
  position = c("bottom", "right", "top", "left"),
  plot = TRUE
)

Arguments

...

Objects to plot. First argument should be a ggplot2 object, as the legend is extracted from this. Other arguments are passed on to arrangeGrob, including named arguments that are not defined for grid_arrange_shared_legend. ggplot2 objects have their legends hidden.

ncol

Integer, number of columns to arrange plots in.

nrow

Integer, number of rows to arrange plots in.

position

'bottom' or 'right' for positioning legend.

plot

Logical, when TRUE (default), draws combined plot on a new page.

Value

gtable of combined plot, invisibly. Draw gtable object using grid.draw.

Author(s)

Originally brought to you by Baptiste AuguiƩ (https://github.com/tidyverse/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs) and Shaun Jackman (original). Stefan McKinnon Edwards added left and top margins.

See Also

g_legend, reposition_legend

Examples

library(ggplot2)
dsamp <- diamonds[sample(nrow(diamonds), 300), ]
p1 <- qplot(carat, price, data = dsamp, colour = clarity)
p2 <- qplot(cut, price, data = dsamp, colour = clarity)
p3 <- qplot(color, price, data = dsamp, colour = clarity)
p4 <- qplot(depth, price, data = dsamp, colour = clarity)
grid_arrange_shared_legend(p1, p2, p3, p4, ncol = 4, nrow = 1)
grid_arrange_shared_legend(p1, p2, p3, p4, ncol = 2, nrow = 2)

# Passing on plots in a grob are not touched
grid_arrange_shared_legend(p1, gridExtra::arrangeGrob(p2, p3, p4, ncol=3), ncol=1, nrow=2)

# We can also pass on named arguments to arrangeGrob:
title <- grid::textGrob('This is grob', gp=grid::gpar(fontsize=14, fontface='bold'))
nt <- theme(legend.position='none')
grid_arrange_shared_legend(p1,
   gridExtra::arrangeGrob(p2+nt, p3+nt, p4+nt, ncol=3), ncol=1, nrow=2,
   top=title)

stefanedwards/lemon documentation built on Jan. 14, 2024, 5:55 a.m.