rggplot2patchwork

Why legend is not showing up in plot layout using patchwork in R?


Based on what I read in this answer , what I am trying to do should work. However, the legend is missing. I want to add a legend in the center of a guide space of two plot spaces.

library(ggplot2)
library(patchwork)

# Create three example ggplots with a common legend
p1 <- ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) + 
  geom_point() + 
  theme(legend.position = "none")

p2 <- ggplot(mtcars, aes(x = hp, y = mpg, color = factor(cyl))) + 
  geom_point() + 
  theme(legend.position = "none")

p3 <- ggplot(mtcars, aes(x = qsec, y = mpg, color = factor(cyl))) + 
  geom_point() +
  theme(legend.position = "none")

p4 <- ggplot(mtcars, aes(x = disp, y = mpg, color = factor(cyl))) + 
  geom_point() +
  theme(legend.position = "none")



design2 <- 
"
ABC
DEE
"

p1 + p2 + p3 + p4 + guide_area() +
  plot_layout(guides = "collect", widths = c(5, 5, 5), heights = c(5, 5), design = design2) 

enter image description here

I was expecting to have the legend where the red question mark is.


Solution

  • Realized answer was in the comments afterwards, but posting for posterity. Just remove theme(legend.position = 'none') and your code works as expected.

    library(ggplot2)
    library(patchwork)
    
    # Create three example ggplots with a common legend
    p1 <- ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) + 
      geom_point()
    
    p2 <- ggplot(mtcars, aes(x = hp, y = mpg, color = factor(cyl))) + 
      geom_point() 
    
    p3 <- ggplot(mtcars, aes(x = qsec, y = mpg, color = factor(cyl))) + 
      geom_point()
    
    p4 <- ggplot(mtcars, aes(x = disp, y = mpg, color = factor(cyl))) + 
      geom_point()
    
    
    
    design2 <- 
      "
    ABC
    DEE
    "
    
    p1 + p2 + p3 + p4 + guide_area() +
      plot_layout(guides = "collect", widths = c(5, 5, 5), heights = c(5, 5), design = design2) 
    

    Created on 2024-10-09 with reprex v2.1.1