Legend on bottom, two rows wrapped in ggplot2 in r

The solution above is presented for a single aesthetic. In some cases, you may want to wrap the legend into rows instead of columns across different aesthetics. For posterity, this is shown below.

library(ggplot2)

ggplot(diamonds, aes(x=carat, y=price, col=clarity, shape=cut)) +
  geom_point() +
  theme(legend.position="bottom")

The legend is cut off below:

enter image description here

To wrap the legend using rows, we specify legend.box="vertical". Below, we also reduce the margin for compactness.

ggplot(diamonds, aes(x=carat, y=price, col=clarity, shape=cut)) +
  geom_point() +
  theme(legend.position="bottom", legend.box="vertical", legend.margin=margin())

enter image description here


You were really close. Try this at the very end:

gg+guides(fill=guide_legend(nrow=2,byrow=TRUE))

Tags:

R

Legend

Ggplot2