Reorder factors for ggplot

A somewhat contrived example . . . first, illustrate the problem:

library(ggplot2)
ggplot(iris)+aes(x=Sepal.Width)+geom_histogram()+facet_grid(Species~.)

Unsorted histogram
How do we get these histograms to be better sorted? The following will reorder the factor variable, Species, by the mean of Sepal.Width:

iris$Species = reorder(iris$Species, iris$Sepal.Width, mean)
ggplot(iris)+aes(x=Sepal.Width)+geom_histogram()+facet_grid(Species~.)

Sorted histogram
Now the histograms are sorted by the mean sepal width.

Tags: , , , ,

One Response to “Reorder factors for ggplot”

  1. hadley Says:

    I hope that in a future version you’ll be able to do

    ggplot(iris)+aes(x=Sepal.Width)+geom_histogram()+facet_grid(reorder(Species, Sepal.Width) ~.)

    directly.

Leave a Reply