How to Change Order of Items in ggplot2 Legend


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 <- data.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 <- data.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 <- data.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

One Reply to “How to Change Order of Items in ggplot2 Legend”

  1. I’m having trouble with ggplot2. I created a plot, but the legend is displaying the numbers in a non-sequential order. The legend currently shows values such as 0 hours, 108 hours,120 hours, 12 hours, 132 hours, 144 hours, 156 hours, 168 hours, 180 hours, 192 hours, 204 hours, 216 hours, 228 hours, 240 hours, 24 hours, 252 hours, 36 hours, 48 hours, 60 hours, 72 hours, 84 hours, 96 hours However, I need the legend to display all hours in sequential order such as 0 hours,12, 24, 36, 48,60,72,84,96, and so on, Could someone please help me with this issue?

Leave a Reply

Your email address will not be published. Required fields are marked *