Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a boxplot in R by the mean of the factor, in a "long" data structure

Tags:

r

boxplot

I'm trying to get a boxplot to progress from the factor with the lowest average value to the factor with the highest average value. Here's a simple example:

a = rnorm(10,mean=3,sd=4)
b = rnorm(10,mean=-1,sd=2)
c = rnorm(10,mean=5,sd=6)
d = rnorm(10,mean=-3,sd=1)
e = rnorm(10,mean=0,sd=.5)

labs = c(rep("a",10),rep("b",10),rep("c",10),rep("d",10),rep("e",10))
mean =     c(rep(mean(a),10),rep(mean(b),10),rep(mean(c),10),rep(mean(d),10),rep(mean(e),10))
data = c(a,b,c,d,e)
df = data.frame(labs,data,mean)
df = df[order(df$mean),]
boxplot(data~labs,data=df)
#They are not ordered
df$labs = ordered(df$labs, levels=levels(df$labs))
boxplot(data~labs,data=df)
#It doesn't work

How can I get the factors to be ordered with the smallest on the left, getting larger as I progress to the right? There are a few threads on this, but their approaches aren't working for me. (perhaps because of my data format?)

BONUS POINTS for helping me to rotate the letters on the x axis by 180 degrees.

Thanks in advance!

like image 733
generic_user Avatar asked Dec 11 '22 17:12

generic_user


2 Answers

boxplot(data~reorder(labs,data),data=df)

enter image description here

EDIT The rotation of text

In the figure and outer margins, text may only be drawn at angles that are multiples of 90◦, and this angle is controlled by the las setting. A value of 0 means text is always drawn parallel to the relevant axis (i.e., horizontal in margins 1 and 3, and vertical in margins 2 and 4). A value of 2 means text is always perpendicular to the relevant axis.

The text drawon in the plot region ( using text) will be controlled by the srt parameter in degree.

  boxplot(data~reorder(labs,data),data=df, las=2,
        names=unique( paste(labs,'long')))

text(x=1,y=5,labels='Use srt to rotate text in the 
       plot region\n but las in figure and outer margins,',
      srt=50,cex=1,font=2)

enter image description here

like image 74
agstudy Avatar answered Apr 30 '23 22:04

agstudy


If you use ggplot2 it is pretty straight forward to do the rotation of the axis text using theme(axis.text.x = element_text(angle= 90)

library(ggplot2)

ggplot(df, aes(x=reorder(labs, data), y = data)) + 
  geom_boxplot() + 
  theme(axis.text.x = element_text(angle=90)) + 
  labs(x= 'x')

enter image description here

The reason your original call to ordered did not work is that you passed the levels from the original data, which were in the incorrect order, the order of the levels should reflect the order you want. That being said reorder is the idiomatic approach in this case.

And a lattice solution, so it doesn't feel forgotten

library(lattice)
bwplot(data~reorder(labs,data), df, scales=  list(x= list(rot = 90)))

enter image description here

like image 23
mnel Avatar answered May 01 '23 00:05

mnel