Sorting a box in R by the average value of the coefficient in the "long" data structure

I am trying to get a boxplot to go from the factor with the lowest average to the ratio with the highest average. Here is 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 factors to order with the smallest on the left, increasing as I move to the right? There are several topics on this, but their approaches do not work for me. (maybe due to my data format?)

BONUS POINTS , helping me rotate the letters along the x axis 180 degrees.

Thanks in advance!

+4
source share
2 answers
 boxplot(data~reorder(labs,data),data=df) 

enter image description here

EDIT Text Rotation

In the figure and the outer edges, the text can only be drawn at angles that are multiples of 90◦, and this angle is controlled by the las setting. A value of 0 means that the text is always drawn parallel to the corresponding axis (that is, horizontally in fields 1 and 3 and vertical at edges 2 and 4). A value of 2 means that the text is always perpendicular to the corresponding axis.

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

  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

+6
source

If you are using ggplot2 , it is quite simple to rotate 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 ordered call didn't work is because you passed levels from the original data that were in the wrong order, the level order should reflect the order you need. In this case, reorder is an idiomatic approach.

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

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

enter image description here

+6
source

All Articles