Gmichael
Gmichael

Reputation: 568

ggplot multiple legends into one box

I am trying to combine multiple partial legends (i.e. for two different features of one plot) legends into one box. My real-life data is a plot made with geom_sf() with fill colors for polygons and a specific border highlighted made with geom_sf()with a line. Since the line is only one feature, it makes no sense to do a separate legend.

REPREX

data(iris)

ggplot(iris)+theme_classic()+
  geom_point(aes(x=Petal.Length, y=Sepal.Length, color=Species, size=Sepal.Width))+
  theme(legend.position=c(0.1,0.75),legend.background=element_rect(fill="white", color="black"), legend.spacing.y=unit(0,"cm"))


### Why doesn't ggplot draw a rectangle around the entire legend?

I managed to reduce the legend spacing, which already makes the plot cleaner, but ...

How can I forego the two separate legend boxes altogether and combine them in one box so that my plot looks cleaner?

Upvotes: 0

Views: 821

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173803

I think you're looking for legend.box.background instead of legend.background:

ggplot(iris) +
  theme_classic() +
  geom_point(aes(x = Petal.Length, y = Sepal.Length, 
                 color = Species, size = Sepal.Width)) +
  theme(legend.position = c(0.1, 0.75), 
        legend.box.background = element_rect(fill = "white", color = "black"), 
        legend.spacing.y = unit(0,"cm"))

enter image description here

Upvotes: 2

Related Questions