grid_arrange_shared_legend: Add a common legend with grid.arrange

View source: R/plot.R

grid_arrange_shared_legendR Documentation

Add a common legend with grid.arrange

Description

Plot several separate plots into a combined figure with a shared legend using grobs and grid.arrange.

Usage

grid_arrange_shared_legend(
  ...,
  nrow = 1,
  ncol = length(list(...)),
  position = c("bottom", "right"),
  legend_reference = 1
)

Arguments

...

Plot objects.

nrow

Integer, number of rows for plotting objects.

ncol

Integer, number of columns for plotting objects.

position

Character vector passed to theme from theme.

legend_reference

An integer that references the plot, in the order provided, to determine where the shared legend should originate from; this is defaulted to 1.

Details

grid.arrange can be more flexible for arranging grobs and plots of different types. If additional parameters are desired, the function may need to be altered. For example, more legend positions could be added to the switch function.

Furthermore, the function assumes that every plot has the same amount of levels for hte factor. If some categories are missing from a plot, ensure the correct plot reference is selected and when making each plot, ensure the legend includes categories that are not plotted. See the example below for some more guidance.

Source

Adapted from Steven Lockton's StackOverflow contribution and Baptiste AuguiƩ.

See Also

https://rpkgs.datanovia.com/ggpubr/reference/ggarrange.html; https://wilkelab.org/cowplot/articles/shared_legends.html

Examples

## Not run: 
library(ggplot2)
library(dplyr)
library(magrittr)

data1 <- iris %>% filter(Species == 'setosa') # Levels not dropped
data2 <- iris %>% filter(Species != 'setosa') # Levels not dropped
levels(data1$Species)
levels(data2$Species)

plot1 <- ggplot(data1, aes(x = Sepal.Width, y = Sepal.Length, color = Species)) +
           geom_point() +
           scale_color_discrete(drop = FALSE) # Ensure that the legend shows all the categories for color!
plot2 <- ggplot(data2, aes(x = Sepal.Width, y = Sepal.Length, color = Species)) +
           geom_point() +
           scale_color_discrete(drop = FALSE)

grid_arrange_shared_legend(plot1,plot2, legend_reference = 1) # Since both plots have the same legend, reference can be either 1 or 2

## End(Not run)

al-obrien/farrago documentation built on April 14, 2023, 6:20 p.m.