首页 文章

在“长”数据结构中,用R的平均值对R中的箱图进行排序

提问于
浏览
4

我试图让箱形图从具有最低平均值的因子发展到具有最高平均值的因子 . 这是一个简单的例子:

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

我怎样才能得到左边最小的因子,随着我向右走?这有几个主题,但他们的方法对我不起作用 . (也许是因为我的数据格式?)

BONUS POINTS 用于帮助我将x轴上的字母旋转180度 .

提前致谢!

2 回答

  • 6

    如果使用 ggplot2 ,使用 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

    您对 ordered 的原始调用无效的原因是您从原始数据中传递了级别,这些级别的顺序不正确,级别的顺序应该反映您想要的顺序 . 这就是说 reorder 在这种情况下是惯用的方法 .

    并且 lattice 解决方案,所以它不会被遗忘

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

    enter image description here

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

    enter image description here

    EDIT The rotation of text

    在图形和外边距中,文本只能以90°的倍数绘制,并且此角度由 las 设置控制 . 值0表示文本始终平行于相关轴绘制(即,边距1和3中的水平,以及边距2和4中的垂直) . 值2表示文本始终垂直于相关轴 .

    绘图区域中的文本绘图(使用文本)将由度数中的 srt 参数控制 .

    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

相关问题