看板 R_Language 關於我們 聯絡資訊
※ 引述《celestialgod (攸藍)》之銘言: ※ 引述《ardodo (米蟲)》之銘言: : 更新一下自己的問題,我想要在ggplot上按照y值總合大小排序我的x類別,以下code : #Data : 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) 推文推太快,複製貼上錯,造成誤會,對不起 levels(hp$class) = levels(hp$class)[ order(tapply(hp$amount, hp$class, sum),decreasing = TRUE)] : #Plotting : p=ggplot(data=hp) : p+geom_bar(binwidth=0.5,stat="identity")+ # : aes(x=class,y=amount,label=amount,fill=year)+theme() -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 123.205.27.107 ※ 文章網址: https://www.ptt.cc/bbs/R_Language/M.1433385843.A.C25.html
ardodo: 感謝cel大回覆,可是我的需求是把ggplot2的x軸 06/04 10:57
ardodo: 依照各類別amount的總合降冪排序,也就是a>c>b>d,而不是 06/04 10:58
ardodo: 單純的更換class的名稱 06/04 10:58
抱歉我神智不清...我意思是refactor,用你要顯示順序改成level的順序 我忘記levels是改名字而已.... hp$class = factor(hp$class, levels = levels(hp$class)[ order(tapply(hp$amount, hp$class, sum),decreasing = TRUE)]) ※ 編輯: celestialgod (123.205.27.107), 06/04/2015 11:06:27 Cel大,我執行您給的那段code結果跟原始數據完全一樣耶,以下code >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) >hp class year amount 1 a 99 100 2 a 100 200 3 a 101 150 4 b 100 50 5 b 101 100 6 c 102 70 7 c 102 80 8 c 103 90 9 c 104 50 10 d 102 90 >hp$class = factor(hp$class, levels = levels(hp$class) [order(tapply(hp$amount, hp$class, sum),decreasing = TRUE)]) >hp class year amount 1 a 99 100 2 a 100 200 3 a 101 150 4 b 100 50 5 b 101 100 6 c 102 70 7 c 102 80 8 c 103 90 9 c 104 50 10 d 102 90 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 163.14.191.172 ※ 文章網址: https://www.ptt.cc/bbs/R_Language/M.1433388252.A.B15.html
celestialgod: 當然一樣,只是改LEVELS順序,以方便畫圖 06/04 11:39