[R] sort boxplot to median

Sundar Dorai-Raj sundar.dorai-raj at PDF.COM
Fri Apr 16 02:27:42 CEST 2004



H. Bromberger wrote:
> Dear guRus,
> I'm stuck and really would appreciate some help. I've already crawled 
> the net...
> I want to do some Boxplot which are sorted by the median and not 
> alphabetically.
> What I did so far:
> x <- subset(mydata, Verwalt.Doku==1, select=c(1, 2))
> P <- plot(x[,1], x[,2], plot=F)
> ???sort(P$stats[3,])???
> bxp(P, col="yellow", las=1, horizontal=T, xlab="Potential")
> 
> Of course it sorts the vector P$stats[3,] but not the rest of the list.
> Thanks in advance, and sorry but I am new to R
> 
> Hubertus
> 

Hi Hubertus,

To make sure bxp (or boxplot) uses the order you want, then the split 
variable must be ordered (see ?ordered). So order the split variable by 
median. E.g.,

R> set.seed(1)
R> z <- data.frame(x = rep(LETTERS[1:3], each = 6), y = rnorm(18))
R> tapply(z$y, z$x, median)
           A           B           C
-0.22140524  0.53160520 -0.03056194
R> z$x <- with(z, ordered(x, levels(x)[order(tapply(y, x, median))]))
R> tapply(z$y, z$x, median)
           A           C           B
-0.22140524 -0.03056194  0.53160520
R> boxplot(y ~ x, data = z)

If you want the descending order, then see ?rev or put a minus sign in 
front of the tapply call.

HTH,

--sundar




More information about the R-help mailing list