Sort boxplot by mean (and not median) in R

Mulone picture Mulone · Mar 16, 2012 · Viewed 9.9k times · Source

I have a simple boxplot, showing the distribution of a score for factor TYPE:

myDataFrame = data.frame( TYPE=c("a","a","b","b","c","c"), SCORE=c(1,1,2,3,2,1) )
boxplot( SCORE~TYPE, data=myDataFrame )

The various types are shown in the order they have in the data frame. I'd like to sort the boxplot by the mean of SCORE in each TYPE (in the example above, the order should be a,c,b).

Any hint?

Answer

Josh O'Brien picture Josh O'Brien · Mar 16, 2012

This is a job for reorder():

myDataFrame$TYPE <- with(myDataFrame, reorder(TYPE, SCORE, mean))
boxplot( SCORE~TYPE, data=myDataFrame )

enter image description here