作者ardodo (米蟲)
看板R_Language
標題[問題] ggplot2請教
時間Wed Jun 3 01:18:59 2015
各位板友好,我的問題是,如何將ggplot繪製的堆疊長條圖,以堆疊的y值總合排序
附圖說明:
http://imgur.com/bwv8fRn
我想要把這張圖的x類別以y總合降冪排列,也就是變成a,c,b,d的順序
請問該怎麼做呢?
以下為我畫出此圖的指令,求解
------------------------------------
##資料準備
hp=read.csv(textConnection(
"class,year,amount
a,99,100
a,100,200
a,101,150
b,100,50
b,101,100
c,102,70
c,102,80
c,103,90
c,104,50
d,102,90"))
hp$year=as.factor(hp$year)
##運算資料
p=ggplot(data=hp)
p+geom_bar(binwidth=0.5,stat="identity")+
aes(x=class,y=amount,label=amount,fill=year)+
theme()
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.161.128.54
※ 文章網址: https://www.ptt.cc/bbs/R_Language/M.1433265541.A.194.html
※ 編輯: ardodo (1.161.128.54), 06/03/2015 01:20:10
→ celestialgod: levels(hp$class) = c("a", "c", "b", "d") 06/03 09:02
→ celestialgod: 不想要手動改可以用 order 跟 tapply 06/03 09:05
→ celestialgod: hp$class[order(tapply(hp$amount, hp$class, sum), 06/03 09:07
→ celestialgod: decreasing = FALSE)] 06/03 09:07
→ celestialgod: levels(hp$class) = hp$class[order(tapply( 06/03 09:07
→ celestialgod: hp$amount, hp$class, sum), decreasing = FALSE)] 06/03 09:08
→ ardodo: cel大您好,我嘗試了您的code,出來的類別只有b,a,a,a耶? 06/04 09:02
→ celestialgod: 詳細的怎麼跑? 可以修改文章附上程式嗎? 06/04 10:13