笑故挽风 2011-03-06 04:20 采纳率: 100%
浏览 1110
已采纳

Ggplot2柱状图中的顺序条

I am trying to make a bar graph where the largest bar would be nearest to the y axis and the shortest bar would be furthest. So this is kind of like the Table I have

    Name   Position
1   James  Goalkeeper
2   Frank  Goalkeeper
3   Jean   Defense
4   Steve  Defense
5   John   Defense
6   Tim    Striker

So I am trying to build a bar graph that would show the number of players according to position

p <- ggplot(theTable, aes(x = Position)) + geom_bar(binwidth = 1)

but the graph shows the goalkeeper bar first then the defense, and finally the striker one. I would want the graph to be ordered so that the defense bar is closest to the y axis, the goalkeeper one, and finally the striker one. Thanks

转载于:https://stackoverflow.com/questions/5208679/order-bars-in-ggplot2-bar-graph

  • 写回答

10条回答 默认 最新

  • 胖鸭 2011-03-06 13:42
    关注

    The key with ordering is to set the levels of the factor in the order you want. An ordered factor is not required; the extra information in an ordered factor isn't necessary and if these data are being used in any statistical model, the wrong parametrisation might result — polynomial contrasts aren't right for nominal data such as this.

    ## set the levels in order we want
    theTable <- within(theTable, 
                       Position <- factor(Position, 
                                          levels=names(sort(table(Position), 
                                                            decreasing=TRUE))))
    ## plot
    ggplot(theTable,aes(x=Position))+geom_bar(binwidth=1)
    

    barplot figure

    In the most general sense, we simply need to set the factor levels to be in the desired order. If left unspecified, the levels of a factor will be sorted alphabetically. However, there are multiple ways to change the order to a specific sequence depending on the situation. For instance, we could do:

    levels(theTable$Position) <- c(...)
    

    and simply list the levels in the desired order on the right hand side. You can also specify the level order within the call to factor as above:

    theTable$Position <- factor(theTable$Position, levels = c(...))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(9条)

报告相同问题?

悬赏问题

  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥15 如何修改pca中的feature函数
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况