How To Fold Legend into Multiple Rows in ggplot2

ggplot2 legend in two rows
ggplot2 legend in two rows

Sometimes when we make a plot with a legend either on top or bottom, it may be too long. In this post, we will learn to fold the long legend into two or more rows (or columns) with ggplot2 in R.

library(tidyverse)
library(gapminder)
# set theme_bw()
theme_set(theme_bw(16))

Example plot with long legend that needs to be wrapped into two rows

We will use gapminder data to make scatter plot with legend that is too long to fit within the plot. By default, ggplot2 places the legend on the right side. However, often one might like to add legend at top or bottom of the plot. Here we add the legend at the bottom using legend.position argument to theme() function.

gapminder %>%
  ggplot(aes(gdpPercap,lifeExp, color=continent)) +
  geom_point() +
  scale_x_log10()+
  theme(legend.position="bottom")

Note that the legend on the bottom of the plot is too long and gets cut out of the plot.

ggplot with long legend at bottom

Fold Legend into Two Rows

We can write the legend in two lines using guides() function in ggplot2. In this scatterplot we colored the points using third variable using “color” argument to aes() function. Since we used color, we need to use color argument with guide_legend() function. Here we can specify the number of rows using nrow=2.

gapminder %>%
  ggplot(aes(gdpPercap,lifeExp, color=continent)) +
  geom_point() +
  scale_x_log10()+
  theme(legend.position = "bottom")+
  guides(color=guide_legend(nrow=2, byrow=TRUE))

And we get scatterplot with two rows for legend’s values at the bottom of the plot.

ggplot2 legend in two rows

Wrapping legend into two rows for legends created by “fill”

Sometimes we might add legend using “fill” argument instead of “color” argument to aes() function while making the plot. In that case we need to use “fill” argument to guides() function.

To show that let us make a grouped boxplot. First, let us simplify gapminder data to make grouped boxplot.

df <- gapminder %>% 
  filter(continent != "Oceania")%>% 
  filter(year %in% c(1952,1962,1972,1982,1992,2002)) %>%
  mutate(year=factor(year))

We make grouped boxplot and add legend with “fill” argument. And use guides() function with fill argument specifying the number of rows for legend.

df %>%
  ggplot(aes(continent,lifeExp, fill=year)) +
  geom_boxplot() +
  theme(legend.position = "top")+
  guides(fill=guide_legend(nrow=2, byrow=TRUE))

In this example, we have two rows of legend on top of the plot.

ggplot2 legend in two rows with guides fill
Exit mobile version