Order and color of bars in ggplot2 barplot

后端 未结 1 964
北海茫月
北海茫月 2020-12-09 04:35

I have a very annoying problem with a stacked bar plot created using ggplot2. There are a couple of similar questions previously asked but after going through

相关标签:
1条回答
  • 2020-12-09 05:10

    The order that bars are drawn (bottom to top) in a stacked barplot in ggplot2 is based on the ordering of the factor which defines the groups. So the Biogeographic.affinity factor must be reordered. Generally we use reorder(if we want to order the factor according to a continuous levels) but here I will just create a new ordered factor similar to what you tried to do.

     biogeo <- transform(biogeo, 
                    Biog.aff.ord  = factor(
                         Biogeographic.affinity ,
                         levels=c( 'Bassian','Widespread','Torresian', 'Eyrean'),
                         ordered =TRUE))
    

    Now if you fill your barplot using Biog.aff.ord rather than the original factor and overriding the default grouping order by defining aes_group_order as Biog.aff.ord order you get the expected result:

    cols <- c(Bassian="darkgrey",Widespread="lightgrey", 
                Torresian="white", Eyrean="black") 
    ggplot(data=biogeo, aes(x=Site, y=Percent,
           order=Biog.aff.ord)) +   ##!! aes_group_order
      geom_bar(stat="identity", colour="black",
            aes(fill=Biog.aff.ord)) +
      scale_fill_manual(values = cols) 
    

    enter image description here

    0 讨论(0)
提交回复
热议问题