Tag Archive for 'factors'

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.