如何使用ggplot显示排名

时间:2016-02-29 11:18:54

标签: r ggplot2 geom-bar

我有以下数据框

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)   

我一直试图将其显示为排名,制作一个翻转的条形图。到目前为止一直很好,但我的酒吧总是按Country订购,我希望它们按Loss排序。

我尝试了一些事情,其中​​包括:

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

拜托,有人能指出我正确的方向吗?在此先感谢!!!

1 个答案:

答案 0 :(得分:1)

您可以使用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()