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

March 23, 2010

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

> levels(diamonds$cut)
[1] "Fair"      "Good"      "Very Good" "Premium"
[5] "Ideal"
> diamonds$cut <- factor(diamonds$cut, levels = rev(levels(diamonds$cut)))
> levels(diamonds$cut)
[1] "Ideal"     "Premium"   "Very Good" "Good"
[5] "Fair"
> ggplot(diamonds, aes(clarity, fill = cut)) + geom_bar()

The legend entries are now in reverse order (and so is the stacking).

Changing Data Stacking Order

The order aesthetic changes the order in which the areas are stacked on top of each other.

The following aligns the order of both the labels and the stacking.

> ggplot(diamonds, aes(clarity, fill = cut, order = -as.numeric(cut))) +
+     geom_bar()

Or, alternatively, reordering the factor levels again:

> diamonds$cut <- factor(diamonds$cut, levels = rev(levels(diamonds$cut)))
> ggplot(diamonds, aes(clarity, fill = cut, order = -as.numeric(cut))) +
+     geom_bar()

To leave a comment for the author, please follow the link and comment on their blog: Learning R. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)