ggplot2: Changing the Default Order of Legend Labels and Stacking of Data

March 23, 2010
By

(This article was first published on Learning R, and kindly contributed to R-bloggers)

“How to change the order of legend labels” is a question that gets asked relatively often on ggplot2 mailing list. A variation of this question is how to change the order of series in stacked bar/lineplots.

While these two questions seem to be related, in fact they are separate as the legend is controlled by scales, whereas stacking is controlled by the order of values in the data.

Recently I spent some time getting my head around this, and below is a quick recap.

Changing the Ordering of Legend Labels

The standard stacked barplot looks like this:

 > library(ggplot2)
 > ggplot(diamonds, aes(clarity, fill = cut)) + geom_bar()

You notice that in the legend “Fair” is at the top and “Ideal” at the bottom. But what if I would like to order the labels in the reverse order, so that “Ideal” would be at the top?

The order of legend labels can be manipulated by reordering the factor levels of the cut variable mapped to fill aesthetic.