按数字变量重新排序因子

4

在使用ggplot2绘图时,我经常遇到这个问题:尝试根据数据框中的数值变量重新排列因子。

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))

我漏掉了什么?
2个回答

5

对于我来说,使用ggplot2 0.9.3可以正常工作,尽管我收到了警告:我认为你想要

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

这里输入图片描述

(为了展示情节而发布,而不是评论...)


我刚从ggplot 0.2.1升级到0.9.3,当我尝试使用ggplot(total.fans, aes(x=reorder(Team, Fans), y=Fans)) + geom_bar()时,出现了以下错误: Error in rename(x, .base_to_ggplot, warn_missing = FALSE) : could not find function "revalue" - tcash21
2
请确保您已经更新了plyr软件包(请参见http://blog.rstudio.org/2012/12/06/ggplot2-plyr-release/)。 - Ben Bolker

3

您也可以在 ggplot() 调用之外使用函数 factor() 重新排序因子,然后再使用 ggplot()

total.fans$Team <- factor(total.fans$Team , levels = total.fans[order(total.fans$Fans), 1])
ggplot(total.fans, aes(x=Team, y=Fans)) + geom_bar(stat="identity")

谢谢,这个解决方案起作用了。我会接受它作为解决方案,但仍然在试图弄清楚其他答案出了什么问题。 - tcash21

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接