Home ยป How to Change Order of Items in ggplot2 Legend

How to Change Order of Items in ggplot2 Legend

by Tutor Aspire

You can use the following syntax to change the order of the items in a ggplot2 legend:

scale_fill_discrete(breaks=c('item4', 'item2', 'item1', 'item3', ...)

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

Example: Change Order of Items in ggplot2 Legend

Suppose we create the following plot in ggplot2 that displays multiple boxplots in one plot:

library(ggplot2)

#create data frame
df frame(team=c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'C'),
                 points=c(6, 8, 13, 16, 10, 14, 19, 22, 14, 18, 24, 26))

#create multiple boxplots to visualize points scored by team
ggplot(data=df, aes(x=team, y=points, fill=team)) +
  geom_boxplot()

To change the order of the items in the legend, we can use the scale_fill_discrete() function as follows:

library(ggplot2)

#create data frame
df frame(team=c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'C'),
                 points=c(6, 8, 13, 16, 10, 14, 19, 22, 14, 18, 24, 26))

#create multiple boxplots to visualize points scored by team
ggplot(data=df, aes(x=team, y=points, fill=team)) +
  geom_boxplot() +
  scale_fill_discrete(breaks=c('B', 'C', 'A'))

ggplot2 boxplot with specific order of items in legend

Notice that the order of the items changed from: A, B, C to B, C, A.

We can also use the labels argument to change the specific labels used for the items in the legend:

library(ggplot2)

#create data frame
df frame(team=c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'C'),
                 points=c(6, 8, 13, 16, 10, 14, 19, 22, 14, 18, 24, 26))

#create multiple boxplots to visualize points scored by team
ggplot(data=df, aes(x=team, y=points, fill=team)) +
  geom_boxplot() +
  scale_fill_discrete(breaks=c('B', 'C', 'A'),
                      labels=c('B Team', 'C Team', 'A Team'))

Notice that the legend labels have changed.

Additional Resources

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

How to Remove a Legend in ggplot2
How to Change Legend Position in ggplot2
How to Change Legend Size in ggplot2
How to Change the Legend Title in ggplot2

You may also like