# Reordering factor levels in R plots

November 3, 2012
By

(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
ispray<-cbind(InsectSprays,order)
#Rename the factor levels of order to reflect the names in spray
levels(ispray\$order)<-c("B","C","F","A","D","E")
#Boxplot using order instead of spray
boxplot(count~order,data=ispray,xlab="spray",ylab="insect count",main="InsectSpray data")