[R] boxplot ranked x labels

Phil Spector spector at stat.berkeley.edu
Mon Oct 18 20:21:33 CEST 2010


Sibylle -
    Since you didn't give a reproducible example, I'll try
to make one that will illustrate what you need to know to
answer your question.
    Suppose we have a variable with levels "four","five",
and "six".

> ff = factor(rep(c('four','five','six'),c(5,7,2)))

Since the table() function will report the levels in the 
same order as boxplot, I'll use that to illustrate my point:

> table(ff)
ff
five four  six
    7    5    2

Suppose we want the levels to appear in the order "four", 
"five","six":

> table(factor(ff,levels=c('four','five','six')))

four five  six
    5    7    2

Now suppose we want to list them in the order of their frequencies:

> table(factor(ff,levels=rev(names(table(ff)))))

  six four five
    2    5    7

In other words, you can have a factor's levels appear in whatever
order you'd like by using the levels= argument to factor.

Hope this helps.
 					- Phil Spector
 					 Statistical Computing Facility
 					 Department of Statistics
 					 UC Berkeley
 					 spector at stat.berkeley.edu


On Mon, 18 Oct 2010, Sibylle Stöckli wrote:

> Dear R users,
>
>
> x-values (EI) = Adw, EG1, LA1, Ad1, LA2, LA3...(14 levels, insect
> stages)
> y-valus = antpop
>
> within the boxplot function x-values are ordered alphabetically
>
> Idea:  x-values ranked by list order (insect stage: Egg stage 1 is
> followed by Larvae 1 and not by Egg stage 2 as it would be in an
> alphabetically order)
>
> Problems with the order(tapply()) function: variable lengths differ
>
> thanks
> Sibylle
>
> R-code (as later insect stages have higher means, ordering was based
> on mean or median...)
> SOPRA<-read.table("SOPRA206_WG_WAE.txt", na.strings="0", header=TRUE)
> ordered<-order(tapply(SOPRA$antpop, SOPRA$EI, mean))
> boxplot(antpop~ordered, data=SOPRA, boxwex=0.20, at=1:14-0.2,
> scales=list(x=list(rot=45)), notch=TRUE, xlab = "EVENT", ylab = "DOY",
> ylim = c(100,350), yaxs ="i", col="red", subset=(wg == "ctrl"))
> boxplot(antpop~ereignis, data=SOPRA, add=TRUE, boxwex=0.20,
> at=1:14+0.2, xaxt="n", notch=TRUE, col="blue", subset=(wg == "scen"))
> legend(1,330, c("SOPRA206 WGctrl", "SOPRA206 WGscen"), fill=c("red",
> "blue"), bty="n")
> text(1,340, "Waedenswil", font=2, pos=4)
>
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>


More information about the R-help mailing list