Ggplot2: cannot sort x-axis by y-value
I have a problem when sorting by x-axis by y 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's the result:
How do I sort my x-axis using cbd, the number of which is sorted in decreasing order from 450, 290, 150, 90. What should I do?
+3
swchen
source
to share
1 answer
You need to edit the function sum
, otherwise it uses the function by default mean
. Then I put -
in front amount
to bring back order.
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()
+12
Jota
source
to share