shared_legend: Share a Common Legend for Multiple Stacked Plots on a Page

View source: R/shared_legend_function.R

shared_legendR Documentation

Share a Common Legend for Multiple Stacked Plots on a Page

Description

This function places a list of ggplot objects into a single object and provides a shared legend for those plots.
Plots can be stacked (ncol = 1) or side=by-side (nrow = 1); defauls to stacked.
Legend can be place on the bottom or right side of the plots; position must be specified in the function call.

This function has been adapted from: https://rdrr.io/github/josiahpjking/jkr/src/R/grid_arrange_shared_legend.R and
https://github.com/tidyverse/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs

Usage

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

Arguments

nrow

number of plot rows (specify both nrow and ncol)

ncol

number of plot columns (specify both nrow and ncol)

position

Position of the legend on the plots, must be specified as "right" or "bottom"

plotlist

A list of plots to be combined. Defaults to NULL.

Examples


x <- rnorm(200, 10, 3)
y <- rnorm(200, 10, 3)
z <- rep(c('Up', 'Down'),200)
test.dat <- as.data.frame(cbind(x, y,z))
fig.1 <- ggplot2::ggplot(test.dat, aes(x,y)) + geom_point(aes(color=z))
fig.2 <- ggplot2::ggplot(test.dat[which(test.dat$x > 5),], aes(x,y)) + geom_point(aes(color=z))
grid_arrange_shared_legend(fig.1, fig.1, ncol=2, position = "bottom")

JenC36/JACtools documentation built on Oct. 20, 2024, 8:05 a.m.