零零乙 2011-03-06 04:20 采纳率: 33.3%
浏览 4229
已采纳

怎么调整Ggplot2柱状图中的顺序条?

我正在尝试做一个柱状图,其中最大的柱状图最接近 y 轴,最短的柱状图最远。表格如下:

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

因此,我试图建立一个条形图,将球员人数根据位置显示:

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

但图表显示的是守门员横杆,然后是防守队员,最后是前锋队员。 、我希望这个图表被排列整齐,使得防守柱最接近 y 轴,守门员柱,最后是射手柱。谢谢。

  • 写回答

10条回答 默认 最新

  • hurriedly% 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条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条