2012-12-25 74 views
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)) 

我缺少什麼?

回答

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") 
+0

感謝這個工作,我會接受解決方案,但仍然試圖找出其他答案出了什麼問題。 – tcash21

5

它爲我的作品與GGPLOT2 0.9.3,雖然我得到警告:我想你想

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

enter image description here

(發佈,而不是評論,所以我可以展示的情節......)

+0

我剛剛從ggplot 0.2.1升級到0.9.3,並試圖ggplot(total.fans,AES(X =重排(隊球迷),Y =風扇))+ geom_bar時(我收到此錯誤) 重命名錯誤(x,.base_to_ggplot,warn_missing = FALSE): 找不到函數「revalue」 – tcash21

+2

請確保您已更新'plyr'軟件包(請參閱http://blog.rstudio.org/ 2012/12/06/ggplot2-plyr-release /) –