Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
677 views
in Technique[技术] by (71.8m points)

r - ggplot2: can't sort x axis by y value

I have problem in sorting x axis by y value in ggplot2: here is the code below

#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)

#Plotting
p=ggplot(data=hp)  
p+geom_bar(binwidth=0.5,stat="identity")+  #
aes(x=reorder(class,amount),y=amount,label=amount,fill=year)+
theme()

Here is the result:

enter image description here

How do I sort my x axis by a c b d, which amount sorted by decreasing from 450, 290, 150, 90. What should I do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to give reorder the sum function, otherwise it defaults to using the mean function. Then, I put a - in front of amount to get the order reversed.

p=ggplot(data=hp)  
p+geom_bar(binwidth=0.5,stat="identity")+  #
aes(x=reorder(class,-amount,sum),y=amount,label=amount,fill=year)+
theme()

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...