在ggplot2条形图中订单栏 [英] Order Bars in ggplot2 bar graph

查看:83
本文介绍了在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)

一般意义上,我们只需要将因子水平设置为所需的顺序即可。根据具体情况,有多种方法可以做到这一点。例如,我们可以这样做:

In the most general sense, we simply need to set the factor levels to be in the desired order. There are multiple ways of doing this 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(...))

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

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