RNewbi
RNewbi

Reputation: 83

reorder data in ggplot

New and stuck with ggplot:

I have the following data:

tribe   rho preference_watermass
1   Luna2   -1.000  hypolimnic
2   OP10I-A1    -1.000  epilimnic
3   B0_FO56C    -0.986  hypolimnic
4   Planctomycetes_FGIDN    -0.943  hypolimnic
5   acIV_IVNEG  -0.943  hypolimnic
6   FTD4J6C01EE04F  -0.941  hypolimnic
7   alll    -0.941  hypolimnic
8   FTD4J6C02HMHDM  -0.928  hypolimnic
9   Planctomycetes_GQLBU    -0.928  hypolimnic
10  acII-A  -0.886  epilimnic
11  LD19_GMKGQ  -0.880  hypolimnic
12  acIV_E2W4O  -0.880  hypolimnic
13  Planctomycetes_AFE3Z    -0.880  epilimnic
14  Bacteriodetes   -0.880  epilimnic
15  FTD4J6C01APQD0  -0.880  epilimnic
16  FTD4J6C02GBAUX  -0.880  epilimnic
17  baII    -0.845  epilimnic
18  FTD4J6C01CJCBG  0.812   transitient
19  Pyxis   0.928   hypolimnic
20  Sphingobacteria_GQB5E   0.928   transitient
21  acI-A_I8OXG 0.943   hypolimnic
22  LD12    0.943   epilimnic

I wanted to make a bargraph where factors(tribes) are sorted according to ascending values of rho.

plot2<-ggplot(data=dfm, aes(x=tribe,y=rho,fill=preference_watermass))+
  geom_bar(stat="identity")+
  coord_flip()+
  labs(y="Spearman correlation rho",x="tribe")+
  scale_fill_manual(values=c("blue", "red", "black"))

enter image description here

Then I tried reordering:

plot2<-ggplot(data=dfm, aes(reorder(tribe,rho,order=TRUE),rho,fill=preference_watermass))+
  geom_bar(stat="identity")+
  coord_flip()+
  labs(y="Spearman correlation rho",x="tribe")+
  scale_fill_manual(values=c("blue", "red", "black"))

But get this one: enter image description here

What am I missing that I can order the values? Thanks for your help!

Upvotes: 2

Views: 1672

Answers (1)

tonytonov
tonytonov

Reputation: 25608

You have to reorder the data itself, not just within aes, as correctly stated by @amzu:

dfm$tribe <- reorder(dfm$tribe, dfm$rho)
plot2

enter image description here

Upvotes: 5

Related Questions