Table of Contents
To re-order items in the ggplot2 legend, you must change the order of the factor levels before creating the plot. This can be done by using the levels function, where you can specify the order in which the levels should appear in the legend. The order of the legend will then match the new order of the factor levels.
You can use the following syntax to change the order of the items in a 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'))
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.
The following tutorials explain how to perform other common operations in ggplot2: