1

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

enter image description here

Fig. 2 enter image description here

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")

enter image description here

Desired Outcome of MWE enter image description here

Brigadeiro
  • 2,649
  • 13
  • 30
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Aug 14 '21 at 23:39
  • @MrFlick just added a MWE that I believe works to reproduce this problem - thanks for the suggestion. – Brigadeiro Aug 14 '21 at 23:52

1 Answers1

0

If you haven't resolved this, you need to use the + instead of the & in your code:

From your mwe:

# note the +
plot1 + plot2 + plot_layout(guides = "collect")

enter image description here

phiver
  • 23,048
  • 14
  • 44
  • 56