# [R] Ordering box plots

Stuart Luppescu slu at ccsr.uchicago.edu
Mon Jan 24 00:37:05 CET 2011

```Hello all, I want box plots by group to display in order of increasing
mean (or median) of each group but can't seem to figure it out and
couldn't find anything on R-seek, either.

My data looks like this:

1  2.24 1002 99999902    NA 0.8600000
2  3.04 1007 43589520     3 0.9400000
3  4.95 2002 39910470     5 1.5300000
4  2.24 2002 39986280     5 1.2755861
5  3.04 2002 40534857     5 1.0551474
6  4.95 2002 40650784     5 1.5300000
7  4.95 1001 40963456     5 1.5300000
8  2.24 2002 41730862     5 0.8642893
9  0.84 2002 41813806     5 1.2282878
10 3.04 2002 41822848     5 1.0551474

I'm plotting meas grouped by unit.

Here are my (unsuccessful) ideas:
1) save the plot data (call it bxp.info) to an object, reorder all the
data according to bxp.info\$data[3,], and then plot it with bxp().
Couldn't figure out how to reorder all the elements of bxp.info (because
they are all different types and lengths?)
2) calculate the means by group, get ordered factors of the group means,
merge the ordered factors back into the original data frame, and plot
the values by the order of the means. Here is the code I used:

by.schl.order <- as.data.frame(cbind(units,as.ordered(order(aggregate(meas.tab[,meas], by=list(meas.tab\$unit), mean, na.rm=T)\$x))))

names(by.schl.order) <- c("unit", "by.schl.plot.order")

meas.tab <- merge(meas.tab, by.schl.order, by="unit")

boxplot(meas.tab[,meas] ~ meas.tab\$by.schl.plot.order)

For some reason, the plot order (by.schl.plot.order) ends up as a
numeric instead of an ordered factor when put in the data frame,

class(meas.tab\$by.schl.plot.order)
[1] "numeric"

and the boxes plot in the original order. I even tried this:

boxplot(meas.tab[,meas] ~ as.ordered(meas.tab\$by.schl.plot.order)

but that didn't do any better. I would think people would want to do
this all the time. There must be an easy way to do it but I can't figure
it out. Can anyone help me?
--
Stuart Luppescu -=- slu .at. ccsr.uchicago.edu
University of Chicago -=- CCSR

It seems that you are facing a very serious
fortune(122) problem.    -- Jean R. Lobry (in
reply to a user that quickly needed help for his
PhD       thesis, without properly checking the
documentation)       R-help (May 2006)

```