通过数值变量对因子重新排序

标签 r ggplot2

在使用 ggplot2 绘图并尝试根据 data.frame 中的数字变量对因子重新排序时,我似乎总是遇到这个问题。

structure(list(Team = structure(1:32, .Label = c("ARI", "ATL", 
"BAL", "BUF", "CAR", "CHI", "CIN", "CLE", "DAL", "DEN", "DET", 
"GB", "HOU", "IND", "JAC", "KC", "MIA", "MIN", "NE", "NO", "NYG", 
"NYJ", "OAK", "PHI", "PIT", "SD", "SEA", "SF", "STL", "TB", "TEN", 
"WAS"), class = "factor"), Fans = c(49L, 145L, 175L, 75L, 104L, 
167L, 101L, 147L, 157L, 304L, 112L, 338L, 200L, 118L, 37L, 60L, 
65L, 225L, 371L, 97L, 163L, 87L, 84L, 102L, 111L, 85L, 422L, 
311L, 63L, 56L, 49L, 271L)), .Names = c("Team", "Fans"), row.names = c(NA, 
-32L), class = "data.frame")

这不会按粉丝数量对球队重新排序:

ggplot(total.fans, aes(x=reorder(Team, Fans), y=Fans)) + geom_bar()

此转换调用也不会更改数据:

transform(total.fans, variable=reorder(Team, -Fans))

我错过了什么?

最佳答案

它适用于 ggplot2 0.9.3,尽管我收到警告:我认为你想要

ggplot(total.fans, aes(x=reorder(Team, Fans),y=Fans)) + 
   geom_bar(stat="identity")

enter image description here

(发帖而不是评论,这样我就可以展示情节......)

关于通过数值变量对因子重新排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14033342/

相关文章:

r - dplyr - 像 rowmeans() 一样使用 mutate()

R - 将多行并排连接成一行

r - 在 R 中识别数据集中的异常值

r - 如何过滤R中具有特定值的参与者?

R:为什么我的 ggplot geom_point() 符号不可见?

r - 使用 ggparty 的决策 TreeMap 边缘的小数位数

r - 从向量中为 data.table 的每一行选取一个随机元素

R:如何将多边形和线段的直线与极坐标结合起来?

r - 实现多位置闪避

r - ggplot2 对象中存储的比例颜色在哪里?