ggplot2 legend in 2 rows

Viewed 63

I was unable to find a solution for putting ggplot2 legend in 2 rows.

Example

library(ggplot2)
theme_set(theme_bw())
data("midwest", package = "ggplot2")

ggplot(midwest, aes(x=area, y=poptotal)) + 
  geom_point(aes(col=state, size=popdensity)) + 
  geom_smooth(method="loess", se=F) + 
  xlim(c(0, 0.1)) + 
  ylim(c(0, 500000)) + 
  labs(y="Population", 
       x="Area", 
       title="") +
  theme(legend.position = "top")

enter image description here

In the above image, I would like to have popdensity annotation on top (first row) and state annotation in the second row.

1 Answers

I think you're looking for theme(legend.box = "vertical") and guide_legend(order = ...)

library(ggplot2)

data("midwest", package = "ggplot2")

ggplot(midwest, aes(x=area, y=poptotal)) + 
  geom_point(aes(col=state, size=popdensity)) + 
  geom_smooth(method="loess", se=F) + 
  xlim(c(0, 0.1)) + 
  ylim(c(0, 500000)) + 
  labs(y="Population", 
       x="Area", 
       title="") +
  theme_bw() +
  theme(legend.position = "top", 
        legend.box = "vertical") +
  guides(size = guide_legend(order = 1), 
         colour = guide_legend(order = 2))

enter image description here

Related