4

在使用 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))

我错过了什么?

4

2 回答 2

5

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

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

在此处输入图像描述

(发布而不是评论,所以我可以展示情节......)

于 2012-12-25T19:24:16.923 回答
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")
于 2012-12-25T19:29:22.890 回答