Search code examples
rggplot2geom-bar

r ggplot stack identity


enter image description here

i want to make this image..

my data is difficult to disclose so i make a arbitrary data.. TnT...

data no total outcome 1 800 40 2 700 30 3 650 27 4 600 25 5 500 20

i tried..

ggplot(data, aes(x=no, y=total))+ your textgeom_bar(stat="identity") your textgeom_bar(stat="identity")+ your textlabs(x="No", y="Total")+ your textscale_y_continuous(breaks=seq(900,100)) + your texttheme_minimal()

i want make

enter image description here

black bar is total, grey bar is outcome..

help me plz..TnT..

i write this topic using papago, so... sentence can be awkward...I ask for your understand.!!


Solution

  • For visualizing the chart that you want, you need to pivot your data.

    You can pivot(make wide data long) with reshape2::melt()

    df <- data.frame(
      no = 1:5,
      total = c(800,700,650,600,500),
      outcome = c(40,30,27,25,20)
    )
    
    require(ggplot2)
    require(reshape2)
    df_long <- melt(df,
                    id.vars='no',
                    measure.vars=c('total','outcome'))
    
    ggplot(df_long, aes(x=no, y=value, fill=variable))+
      geom_col()+
      scale_fill_manual(values = c('black','grey')) +
      scale_y_continuous(breaks=seq(0,900,100))+
      theme_minimal() +
      labs(x='No', y='Total')
    

    Note that geom_bar(stat='identity') is equal to geom_col().

    enter image description here