Search code examples
rggplot2bar-chartgeom-bar

How can I stack bars manually with already counted splits using ggplot2?


I have the following dataframe, and I am trying to use ggplot2 to make a stacked barplot split into "Early" and "Late". The column "Count" is the total count (Early+Late).

    Stage   Count   Early   Late
------------------------------------
    PreMBT  2208    1539    669
    Dome    2050    1507    543 
    Shield  1939    1442    479
    Bud     1865    1377    488

I want the Stage on the x axis, and Count on the y axis. However, I want to break up the bars by having Early be one color and Late be another color, with the legend having these 2 as well. I have tried many things but it is not working...which is why I was wondering if there's a manual way to separate it? Any help appreciated! This is what I have so far (which is not broken up by Early/Late yet):

densityplot <-ggplot(data, aes(x=Stage,fill=Stage,weight=Count))+geom_bar()

but when I try doing fill= Early, it doesn't work.


Solution

  • I excluded Count:

    mlt = melt(df, id = "Stage")
    mlt
    
    ggplot(mlt, aes(x=Stage, y = value, fill = variable))+
      geom_bar(position = "stack", stat = "identity")
    

    enter image description here