Change Number of Rows and Columns in Legend Keys in ggplot2

This tutorial explains how to split a long legend into multiple rows or columns.


Start with a long legend

Let’s first build an ordered stacked bar plot, with a long vertical legend positioned at the top left corner of the plot. (Check here to learn fundamental techniques to reorder graphic elements, and here to learn advanced reordering based on group statistics as used in this article)

# packages and global themelibrary(ggplot2)library(dplyr)library(forcats) # to reorder rows
theme_set(theme_minimal(base_size = 14))
p <- mpg %>% # reorder bars based on the counts in each manufacturer mutate(manufacturer = fct_reorder( manufacturer, manufacturer, length)) %>% ggplot(aes(manufacturer, fill = class)) + geom_bar(color = "black") + scale_fill_brewer(palette = "Pastel2") + theme( # rotate and right justify axis label axis.text.x = element_text(angle = 45, hjust = 1), legend.position = c(.3, .7))p

Divide legend into multiple rows

p + guides(fill = guide_legend(nrow = 3))

Equivalently, the guides() can be written in its associated scale_* function.

p + scale_fill_brewer(  palette = "Pastel2",  # Note to use 'guide', without the plural 's'  guide = guide_legend(nrow = 3)) 

Adjust legend title position

With a more horizontally oriented legend, it is desirable to center justify the legend title.

p + guides(fill = guide_legend(  nrow = 3,  title.theme = element_text(hjust = .5, face = "bold"))) 

Or consider putting the legend title on the left side and rotated at 90°.

p + guides(fill = guide_legend(  nrow = 3,   title.position = "left",  title.theme = element_text(    hjust = .5, face = "bold", angle = 90)))