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

前端 未结 4 639
情话喂你
情话喂你 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:49

    Define new data frame with all combinations of "Category" and "Reason", merge with data of "Species" from data frame "Animals". Adapt ggplot by correct scale_x_discrete:

    Animals3 <-  expand.grid(Category=unique(Animals$Category),Reason=unique(Animals$Reason))
    Animals3 <- merge(Animals3,Animals,by=c("Category","Reason"),all.x=TRUE)
    Animals3[is.na(Animals3)] <- 0
    Animals3 <- Animals3[order(Animals3$Category,-Animals3$Species),]
    ggplot(Animals3, aes(x=Animals3$Reason, y=Species, fill = Category)) + geom_bar(stat="identity", position = "dodge") + scale_x_discrete(limits=as.character(Animals3[Animals3$Category=="Decline","Reason"]))
    

提交回复
热议问题