
When you make a bar plot for categorical (i.e., factor) variables, probably you want to order the levels of variable in some way.
The basic idea is that making data.frame in the order you want. But this does not woks well, because the levels are reordered alphabetically. Actually, this is not a power of ggplot2, but the general behavior of factor variable.
ggplot2 uses the order of levels of factor variable to determine the order of category.
In R, there are many ways to specify the order of factors.
# sample data.
d <- data.frame(Team1=c("Cowboys", "Giants", "Eagles", "Redskins"), Win=c(20, 13, 9, 12))
# basic layer and options
p <- ggplot(d, aes(y=Win)) + opts(axis.text.x=theme_text(angle=90, hjust=1))
# default plot (left panel)
# the variables are alphabetically reordered.
p + geom_bar(aes(x=Team1), stat="identity") + opts(title="Default")
# re-order the levels in the order of appearance in the data.frame
d$Team2 <- factor(d$Team1, as.character(d$Team1))
# same as
# d$Team2 <- factor(d$Team1, c("Cowboys", "Giants", "Eagles", "Redskins"))
# plot on the re-ordered variables (Team2) (middle panel)
p + geom_bar(aes(x=Team2), data=d, stat="identity") + opts(title="Order by manual")
# re-order by variable Win
# the variables are re-orderd in the order of the win
d$Team3 <- reorder(d$Team1, d$Win)
# plot on the re-ordered variables (Team3) (right panel)
p + geom_bar(aes(x=Team3), data=d, stat="identity") + opts(title="Order by variable")
Note that re-ordering the factor is also useful to specifying the order of facet and so on.
You made my day! I was looking for the same topic on a boxplot, and it works the same way. Very well explained. Thank you so much, Sascha
Great, just what I was looking for, thanks.
[...] How to rearrange the order of factors in R for plotting with ggplot2 [...]
Thank you for this. Frederic
[...] has gone ahead and solved one of my main gripes with ggplot2. This needs to be more prominent in the official documentation [...]
This post saved me from my main bugbear with ggplot2. Thanks!
One question: what wordpress extension do you use to display code as you have above?
“This post saved me from my main bugbear with ggplot2. Thanks!”
+1!
This post solved my problem! Thank you!