问题描述
我正在尝试制作一个条形图,其中最大的条最靠近 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
推荐答案
排序的关键是按照你想要的顺序设置因子的水平.不需要有序因子;有序因子中的额外信息不是必需的,如果这些数据用于任何统计模型,则可能会导致错误的参数化 -mdash;多项式对比不适用于诸如此类的名义数据.
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. 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条形图中的订单条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!