Search code examples
rggplot2patchwork

How to avoid redundant entries in legend using ggplot and patchwork?


I am combining ggplots using the patchwork library and I am wondering if there is a way to eliminate redundant color entries for error bars and points. See and example using mtcars below.

# load data and libs
data("mtcars")

library(ggplot2)
library(patchwork)

ggplot(mtcars,aes(mpg,hp,color = factor(am),size = wt)) +
  geom_point() +
  
ggplot(mtcars,aes(mpg,hp,color = factor(am),shape = factor(gear))) +
  geom_point() +
  plot_layout(guides = "collect")

enter image description here

This produces a graph with a single legend entry for colors. However when I add error bars to one of the graphs:

ggplot(mtcars,aes(mpg,hp,color = factor(am),size = wt)) +
  geom_point() +
  
ggplot(mtcars,aes(mpg,hp,color = factor(am),shape = factor(gear))) +
  geom_point() +
  geom_errorbar(aes(xmin = mpg-(mpg*0.2),
                    xmax =mpg+(mpg*0.2))) +
  plot_layout(guides = "collect")

enter image description here

Now I get one legend for point color and a redundant error bar color label. I would like just one label for color. Is there anyway to get just a single color entry in the legend without dropping shape or size from the legend?


Solution

  • Legends will only get collected when they are identical. Hence, if you want only one color legend you have to make them identical which as one option could be achieved by adding show.legend=FALSE to geom_errorbar:

    library(ggplot2)
    library(patchwork)
    
    p1 <- mtcars |> 
      ggplot(aes(mpg, hp, color = factor(am), size = wt)) +
      geom_point()
    
    p2 <- mtcars |> 
      ggplot(aes(mpg, hp, color = factor(am), shape = factor(gear))) +
      geom_point() +
      geom_errorbar(aes(
        xmin = mpg - (mpg * 0.2),
        xmax = mpg + (mpg * 0.2)
      ), show.legend = FALSE)
    
    p1 + p2 +
      plot_layout(guides = "collect")