ggplot2: add ordered category labels to stacked bar chart

前端 未结 3 825
春和景丽
春和景丽 2021-01-26 09:55

I\'m trying to make a stacked bar chart of microbiome abundance (dataset at the end). Since there are a lot of classes, it\'s hard to tell the difference between colors, so I wa

相关标签:
3条回答
  • 2021-01-26 10:10

    As @Lyngbakr suggested you can fix this with the label aesthetic either in the main plot function or the geom_text as below.

    ggplot(abun, aes(x = status, y = freq, fill = Order)) +
        geom_bar(stat = "identity", col = "black") +
        ylab("Frequency (%)") +
        geom_text(aes(label = Order), position = position_stack(vjust = 0.5)) +
        theme(text = element_text(size = 20, face = "bold"), legend.text = element_text(size = 12, face = "plain"))
    

    This occurs becasue the default grouping in geom_text (see: http://ggplot2.tidyverse.org/reference/aes_group_order.html) does not work here and needs to be specified with an aesthetic.

    I had a very similar problem myself: Out of order text labels on stack bar plot (ggplot)

    0 讨论(0)
  • 2021-01-26 10:18

    Changed the geom_text call thus:

    ggplot(abun,aes(x=status,y=freq,fill=Order))+
    geom_bar(stat="identity",col="black")+
    ylab("Frequency (%)")+
    geom_text(label=c(rev(levels(abun$Order)),rev(levels(abun$Order))),position=position_stack(vjust=0.5))+
    theme(text=element_text(size=20,face="bold"),legend.text=element_text(size=12,face="plain"))
    

    yielding:

    It seems geom_text cycles through all factor levels without regard for x. Fixing this required running through the reversed list twice: label=c(rev(levels(abun$Order)),rev(levels(abun$Order)))

    So for n factor levels under the x mapping, include c(rev(levels(LabelText))) n times.

    Thanks to @Lyngbakr for getting me on the right track.

    0 讨论(0)
  • 2021-01-26 10:35

    Does this work?

    ggplot(abun, aes(x = status, y = freq, fill = Order, label = Order)) +
      geom_bar(stat = "identity", col = "black") +
      ylab("Frequency (%)") +
      geom_text(position = position_stack(vjust = 0.5)) +
      theme(text = element_text(size = 20, face = "bold"), legend.text = element_text(size = 12, face = "plain"))
    
    0 讨论(0)
提交回复
热议问题