ggplot2条形图中的订单栏

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轴,守门员一个,最后是前锋一个。谢谢


慕姐8265434
浏览 624回答 4
4回答

沧海一幻觉

排序的关键是按所需顺序设置因子的级别。不需要有序因子; 有序因子中的额外信息不是必需的,如果在任何统计模型中使用这些数据,可能会导致错误的参数化 - 多项式对比不适合这样的标称数据。## set the levels in order we wanttheTable <- within(theTable,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Position <- factor(Position,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; levels=names(sort(table(Position),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; decreasing=TRUE))))## plotggplot(theTable,aes(x=Position))+geom_bar(binwidth=1)条形图在最一般意义上,我们只需要将因子水平设置为所需的顺序。如果未指定,则因子的级别将按字母顺序排序。您也可以在上面的因子调用中指定级别顺序,也可以采用其他方式。theTable$Position <- factor(theTable$Position, levels = c(...))

芜湖不芜

@GavinSimpson:这reorder是一个强大而有效的解决方案:ggplot(theTable, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;aes(x=reorder(Position,Position, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;function(x)-length(x))))&nbsp;+ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;geom_bar()

犯罪嫌疑人X

使用scale_x_discrete (limits = ...)指定的巴左右。positions&nbsp;<-&nbsp;c("Goalkeeper",&nbsp;"Defense",&nbsp;"Striker")p&nbsp;<-&nbsp;ggplot(theTable,&nbsp;aes(x&nbsp;=&nbsp;Position))&nbsp;+&nbsp;scale_x_discrete(limits&nbsp;=&nbsp;positions)

森林海

我认为已经提供的解决方案过于冗长。使用ggplot进行频率排序条形图的更简洁方法是ggplot(theTable,&nbsp;aes(x=reorder(Position,&nbsp;-table(Position)[Position])))&nbsp;+&nbsp;geom_bar()它与Alex Brown的建议相似,但有点短,无需任何函数定义。更新我认为我的旧解决方案当时很好,但是现在我宁愿使用forcats::fct_infreq哪种方式按频率排序因子水平:require(forcats)ggplot(theTable,&nbsp;aes(fct_infreq(Position)))&nbsp;+&nbsp;geom_bar()
打开App,查看更多内容
随时随地看视频慕课网APP