grid_arrange_shared_legend | R Documentation |
Plot several separate plots into a combined figure with a shared legend using grobs and grid.arrange
.
grid_arrange_shared_legend(
...,
nrow = 1,
ncol = length(list(...)),
position = c("bottom", "right"),
legend_reference = 1
)
... |
Plot objects. |
nrow |
Integer, number of rows for plotting objects. |
ncol |
Integer, number of columns for plotting objects. |
position |
Character vector passed to |
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. |
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.
Adapted from Steven Lockton's StackOverflow contribution and Baptiste AuguiƩ.
https://rpkgs.datanovia.com/ggpubr/reference/ggarrange.html; https://wilkelab.org/cowplot/articles/shared_legends.html
## 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)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.