Search code examples
rggplot2patchwork

Keep just one key/legend in patchwork ggplots


The following code produces a patchwork plot:

library(tidyverse)
library(patchwork)
mtboxes <- mtcars |> 
  select(-cyl) |> 
  imap(~ ggplot() +
        geom_boxplot(aes(y = .x, fill = factor(mtcars$cyl))) +
        labs(title = .y, x = NULL, y = NULL))
mtboxes <- mtboxes |> Reduce(`+`, x = _)
mtboxes

enter image description here

There's a legend on each boxplot which is repetitive. I would like to include one of these legends, ideally along the top, right side or bottom, then clear from the rest. How can I do that?


Solution

  • Use + plot_layout(guides = "collect"):

    library(tidyverse)
    library(patchwork)
    
    mtboxes <- mtcars |>
      select(-cyl) |>
      imap(~ ggplot() +
        geom_boxplot(aes(y = .x, fill = factor(mtcars$cyl))) +
        labs(title = .y, x = NULL, y = NULL))
    mtboxes <- mtboxes |> Reduce(`+`, x = _) + plot_layout(guides = "collect")
    
    mtboxes