I want to collect legends for 9 ggplots using the patchwork
package. The legends have different underlying values (See Fig. 1) but all correspond with the same value labels (See Fig. 2). Is it possible to collect these legends? Using plot_layout(guides = "collect")
does not work.
Fig. 1
The code I am using:
library(patchwork)
(p1 | p2 | p3 | p4) / (p5 | p6 | p7 | p8 | p9) &
scale_color_brewer(labels = c("-2 SD", "-1 SD", "Mean", "+1 SD", "+2 SD"),
palette = "RdYlBu") &
scale_fill_brewer(labels = c("-2 SD", "-1 SD", "Mean", "+1 SD", "+2 SD"),
palette = "RdYlBu") &
plot_layout(guides = "collect")
Minimal Working Example
library(ggplot2)
library(patchwork)
plot1 <- ggplot(data = mtcars %>% mutate(cyl = as.factor(cyl)),
mapping = aes(x = wt, y = mpg, group = cyl, color = cyl)) +
geom_smooth(method = "lm")
plot2 <- ggplot(data = mtcars %>% mutate(cyl = as.character(cyl)),
mapping = aes(x = wt, y = mpg, group = cyl, color = cyl)) +
geom_smooth(method = "lm")
plot1 + plot2 &
plot_layout(guides = "collect")