How to Create a Legend in ggplot2 with Multiple Rows

Creating a legend in ggplot2 with multiple rows requires the use of the ‘guides’ function, which allows the user to specify the number of rows and the order in which the legend items appear. Additionally, the user must provide a vector of labels, colors, and symbols to be used in the legend. Finally, the ‘theme’ function can be used to customize the appearance of the legend, such as font size, border, or background color.


You can use the following syntax to create a legend in ggplot2 with multiple rows:

ggplot(df, aes(x=x_var, y=y_var, color=group_var)) +
  geom_point() +
  guides(color=guide_legend(nrow=2, byrow=TRUE)) 

The value for the nrow argument specifies the number of rows to use in the legend.

The following example shows how to use this syntax in practice.

Example: Create Legend in ggplot2 with Multiple Rows

Suppose we have the following data frame in R that contains information about various basketball players:

#create data frame
df <- data.frame(team=c('Mavs', 'Heat', 'Nets', 'Lakers', 'Suns', 'Cavs'),
                 points=c(24, 20, 34, 39, 28, 29),
                 assists=c(5, 7, 6, 9, 12, 13))

#view data frame
df

    team points assists
1   Mavs     24       5
2   Heat     20       7
3   Nets     34       6
4 Lakers     39       9
5   Suns     28      12
6   Cavs     29      13

If we create a scatter plot in ggplot2 without specifying the number of rows to use in the legend, ggplot2 will place one label on each line by default:

library(ggplot2)

#create default scatterplot
ggplot(df, aes(x=assists, y=points, color=team)) +
  geom_point(size=3)

In order to create a legend with multiple rows, we must use the guides() function with the nrow argument:

library(ggplot2)

#create scatterplot with two rows in legend
ggplot(df, aes(x=assists, y=points, color=team)) +
  geom_point(size=3) +
  guides(color=guide_legend(nrow=2, byrow=TRUE)) 

Notice that the legend now has two rows.

If we’d like to change the location of the legend as well, we can use the theme() function with the legend.position argument:

library(ggplot2)

#create scatterplot with two rows in legend
ggplot(df, aes(x=assists, y=points, color=team)) +
  geom_point(size=3) +
  theme(legend.position='bottom') +
  guides(color=guide_legend(nrow=2, byrow=TRUE)) 

The following tutorials explain how to perform other common operations in ggplot2:

x