作者ardodo (米虫)
看板R_Language
标题Re: [问题] ggplot2请教
时间Thu Jun 4 11:24:10 2015
※ 引述《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://webptt.com/cn.aspx?n=bbs/R_Language/M.1433385843.A.C25.html
1F:推 ardodo: 感谢cel大回覆,可是我的需求是把ggplot2的x轴 06/04 10:57
2F:→ ardodo: 依照各类别amount的总合降幂排序,也就是a>c>b>d,而不是 06/04 10:58
3F:→ 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://webptt.com/cn.aspx?n=bbs/R_Language/M.1433388252.A.B15.html
4F:推 celestialgod: 当然一样,只是改LEVELS顺序,以方便画图 06/04 11:39