ggplot2条形图中的顺序条 [英] Order Bars in ggplot2 bar graph

查看:28
本文介绍了ggplot2条形图中的顺序条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个条形图,其中最大的条形图最接近 y 轴,最短的条形图最远.所以这有点像我的表

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)

但图表首先显示的是守门员栏,然后是防守栏,最后是前锋栏.我希望对图表进行排序,以便防守条最接近 y 轴,守门员最接近,最后是前锋.谢谢

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

推荐答案

排序的关键是按照你想要的顺序设置因子的水平.不需要有序因子;有序因子中的额外信息不是必需的,如果在任何统计模型中使用这些数据,则可能会导致错误的参数化 —多项式对比不适用于此类标称数据.

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)

在最一般的意义上,我们只需将因子水平设置为所需的顺序.如果未指定,因子的级别将按字母顺序排序.你也可以像上面那样在 factor 调用中指定级别顺序,其他方式也是可能的.

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. You can also specify the level order within the call to factor as above, and other ways are possible as well.

theTable$Position <- factor(theTable$Position, levels = c(...))

这篇关于ggplot2条形图中的顺序条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆