grouped barplot: order x-axis & keep constant bar width, in case of missing levels

前端 未结 4 634
情话喂你
情话喂你 2021-01-21 14:12

Here is my script (example inspired from here and using the reorder option from here):

library(ggplot2)
Animals <- read.table(
  header=TRUE, tex         


        
4条回答
  •  灰色年华
    2021-01-21 14:41

    First let's fill your data.frame with missing combinations like this.

    library(dplyr)
    Animals2 <- expand.grid(Category=unique(Animals$Category), Reason=unique(Animals$Reason)) %>% data.frame %>% left_join(Animals)
    

    Then you can create an ordering variable for the x-scale:

    myorder <- Animals2 %>% filter(Category=="Decline") %>% arrange(desc(Species)) %>% .$Reason %>% as.character
    

    An then plot:

    ggplot(Animals2, aes(x=Reason, y=Species, fill = Category)) + 
      geom_bar(stat="identity", position = "dodge") + scale_x_discrete(limits=myorder)
    

提交回复
热议问题