ggplot:图例级别,在x轴上获得正确的顺序

时间:2017-04-21 14:29:24

标签: r ggplot2 legend levels

我尝试使用代码绘制标准条形图:

    dat2<-data.frame(Ramp = rep(c("Low","Mid","MidHigh", "High"),each = 2),
             score=rep(c("Average Score", "Top Score"), 2),
             score.1=c(23.89,23.89,7.31,2.54,10.18,8.70,
                      3.17,2.00))

    plot2<- ggplot(data=dat2,aes(x=score,  y=score.1, fill = Ramp)) + 
      geom_bar(stat="identity", position = position_dodge(), 
               width = .8) +
      theme_classic() 

    colour2<- scale_fill_grey(limits = c("Low","Mid","MidHigh","High"))

    plot2 + colour2                  

这会产生一个图表,其中图例的顺序正确,但x轴中的因子的顺序不正确。如何更改它以匹配图例的顺序?

目前情节如下:

enter image description here

1 个答案:

答案 0 :(得分:0)

将Ramp变量更改为因子变量,指定级别。

RampF <- factor(c("Low","Mid","MidHigh", "High"), levels = c("Low","Mid","MidHigh", "High"))

dat2<-data.frame(Ramp = rep(RampF,each = 2),
                 score=rep(c("Average Score", "Top Score"), 2),
                 score.1=c(23.89,23.89,7.31,2.54,10.18,8.70,
                           3.17,2.00))

plot2<- ggplot(data=dat2,aes(x=score,  y=score.1, fill = Ramp)) + 
    geom_bar(stat="identity", position = position_dodge(), 
             width = .8) +
    theme_classic() 

colour2<- scale_fill_grey(limits = c("Low","Mid","MidHigh","High"))

plot2 + colour2