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]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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")

 

To leave a comment for the author, please follow the link and comment on their blog: Eldon Prince » R-bloggers.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.



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

Sponsors

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)