J. Doe
J. Doe

Reputation: 1750

ggplot - two legend boxes?

This code:

mtcars %>% 
  group_by(carb, gear, am) %>% 
  summarise(mpg = mean(mpg)) %>% 
  ggplot(aes(x = carb, y = mpg, color = as.factor(gear), linetype = as.factor(am), group = interaction(gear, am)))+
  geom_line()+
  geom_point()+
  theme(legend.box.background = element_rect(color = "black", size = 1))

Produces the following image:

enter image description here

However, I would like the color legend and the linetype legend to be in separate legend boxes. I made the desired output in Paint and I am wondering how to achieve this via ggplot:

enter image description here

Upvotes: 1

Views: 68

Answers (1)

stefan
stefan

Reputation: 125952

Separate legend boxes can be achieved by using legend.background instead of legend.background.box. This gives you boxes around each legend but the size of the box depends on the content e.g. the length of the legend title and key labels. To get boxes of equal width you can add some spaces to the legend title via e.g. stringr::str_pad to get titles of equal width. Try this:

library(ggplot2)
library(dplyr)

mtcars %>% 
  group_by(carb, gear, am) %>% 
  summarise(mpg = mean(mpg)) %>% 
  ggplot(aes(x = carb, y = mpg, color = as.factor(gear), linetype = as.factor(am), group = interaction(gear, am)))+
  geom_line()+
  geom_point()+
  labs(linetype = stringr::str_pad("as.factor(am)", 15), color = stringr::str_pad("as.factor(gear)", 15)) +
  theme(legend.background = element_rect(color = "black", size = 1))
#> `summarise()` regrouping output by 'carb', 'gear' (override with `.groups` argument)

Upvotes: 1

Related Questions