Elliot
Elliot

Reputation: 67

Common legend with ggarrange with different elements in each plot

I am trying to combine the legends of several plots into one plot using ggarrange. However, some of the elements in plot 1 are not in plot 2 and vice versa. Therefore, the common.legend option from ggarrange does not work. My code (minimal working example) is as follows:

library(tidyverse)
library(ggpubr)

data("mtcars")

mtcars1 <- mtcars %>%  
  filter(gear == 3 | gear ==4)

p1 <- ggplot(mtcars1, aes(x=wt, y=mpg, color = factor(gear)))+
  geom_point()+
  scale_color_manual(values = c('red', 'blue'))

mtcars2 <- mtcars %>%  
  filter(gear == 3 | gear ==5)

p2 <- ggplot(mtcars2, aes(x=wt, y=mpg, color = factor(gear)))+
  geom_point()+
  scale_color_manual(values = c('red', 'green'))

ggarrange(p1,p2, common.legend = TRUE)

This results in the following plot:

enter image description here

The problem here is that the common legend does not contain the green color (i.e. gear 5). I am wondering how I can create a combined common legend that includes all elements.

In addition, I would like to have a way to group the legend with for example an accolade. So suppose I have the following legend

gear 3 low 4 low 5 medium

then I would like to combine the two lows into one low with an accolade or something similar. Like this:

gear 3 } low 4

5 } medium

Upvotes: 2

Views: 3291

Answers (1)

Mohanasundaram
Mohanasundaram

Reputation: 2949

While considering the gear variable as factor, specify three levels even though the third level is not available in the data set. Then, in scale_color_manual, specify the colors for the values individually and include the argument drop = FALSE).

mtcars1 <- mtcars %>%  
  filter(gear == 3 | gear ==4)

p1 <- ggplot(mtcars1, aes(x=wt, y=mpg, color = factor(gear, levels = c(3, 4, 5))))+
  geom_point(show.legend = TRUE)+
  scale_color_manual(name = 'Gear', 
                     values = c("3" = 'red', "4" = 'blue', "5" = 'green'),
                     drop = FALSE)

mtcars2 <- mtcars %>%  
  filter(gear == 3 | gear ==5)

p2 <- ggplot(mtcars2, aes(x=wt, y=mpg, color = factor(gear, levels = c(3, 4, 5))))+
  geom_point(show.legend = TRUE) +
  scale_color_manual(name = 'Gear', 
                     values = c("3" = 'red', "4" = 'blue', "5" = 'green'),  
                     drop = FALSE)

ggarrange(p1,p2, common.legend = TRUE)

Output:

enter image description here

Upvotes: 4

Related Questions