Reordering factor levels in R plots

November 3, 2012

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

A few days ago a post doctoral researcher asked me if I could help him reorder the factor levels on a bar chart. The problem is that R automatically alphabetizes factor levels. I thought this would be fairly straight-forward but I was wrong. If you have a more elegant solution to this problem please comment, but this is my best workaround. I will use the InsectSprays data and box plots to illustrate the problem and my solution.

#The problem
#Boxplot of how many insect counts there are for each insect spray
boxplot(count~spray,data=InsectSprays,xlab="spray",ylab="insect count",main="InsectSpray data")
#What if we would like a different order than A,B,C,D,E,F?
#The solution
#Make a new factor that reflects the desired order
#For this example, A should be the 4th, B the 1st and so on
order<-as.factor(rep(c(4,1,2,5,6,3), each=12))
#Column bind order to the existing InsectSprays data
#Rename the factor levels of order to reflect the names in spray 
#Boxplot using order instead of spray
boxplot(count~order,data=ispray,xlab="spray",ylab="insect count",main="InsectSpray data")


To leave a comment for the author, please follow the link and comment on their blog: Eldon Prince » R-bloggers. 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)