samyandi
samyandi

Reputation: 151

How to display ranking using ggplot

I have the following data frame

Country<-c("Chile_T", "Canada_T", "El Salvador_N", "Finland_N", "Germany_N", "Germany_T")
Loss<-c(1.14e-06, 6.14e-07, 8.93e-09, 8.93e-09, 1.05e-10, 1.25e-11)
df<- data.frame(Country, Loss)   

I have been trying to display this as a ranking, making a flipped-over bargraph. So far so good BUT my bars always get ordered by Country and I would like them ordered by Loss.

I have tried a few things, among others, this:

df <- within(df, Loss <- factor(Loss,levels=names(sort(table(Loss), decreasing=TRUE))))

ggplot(data=df, aes(x=Country, y=Loss))+
  geom_bar(stat = "identity", width=0.95, fill="black")+
  labs(x = "", y = "")+
  coord_flip()+
  scale_y_discrete(breaks=NULL)+
  theme (legend.position="none", 
         axis.text.x  = element_blank(), 
         axis.text.y  = element_text(size=17), axis.title.y=element_text(size=17))

Please, can someone point me in the right direction? Thanks in advance!!!

Upvotes: 0

Views: 4411

Answers (1)

lukeA
lukeA

Reputation: 54247

You could use reorder:

Country<-c("Chile_T", "Canada_T", "El Salvador_N", "Finland_N", "Germany_N", "Germany_T")
Loss<-c(1.14e-06, 6.14e-07, 8.93e-09, 8.93e-09, 1.05e-10, 1.25e-11)
df<- data.frame(Country, Loss)   
library(ggplot2)
ggplot(data=df, aes(x=reorder(Country, Loss), y=Loss))+
  geom_bar(stat = "identity", width=0.95, fill="black") + 
  coord_flip()

Upvotes: 3

Related Questions