[Solved] Stacked bar chart in R [closed]


Please have a look at how to ask questions on SO and how to provide data/examples. It makes it a lot easier for people to help you if we have all the information ready to go.

The data

I’ve produced a table using some of your data:

library(tidyverse)

df <- tribble(~absent, ~present, ~total, ~session,
        15,8,3,'s1',
        12,11,23,'s2',
        12,10,23,'s4',
        14,9,23,'s5',
        18,5,23,'s6',
        17,6,23,'s7')

Gathering

In terms of producing the chart, first you need to organise your data by calling gather so that you can pass the present/absent variable to the fill method in ggplot.

gather(df, key, value, -total, -session)

This arranges your data like so:

   total session key     value
   <dbl> <chr>   <chr>   <dbl>
 1    3. s1      absent    15.
 2   23. s2      absent    12.
 3   23. s4      absent    12.
 4   23. s5      absent    14.
 5   23. s6      absent    18.
 6   23. s7      absent    17.
 7    3. s1      present    8.
 8   23. s2      present   11.
 9   23. s4      present   10.
10   23. s5      present    9.
11   23. s6      present    5.
12   23. s7      present    6.

Plotting

Then you can call ggplot to create a column chart with the following:

  ggplot(df, aes(x = session, y = value)) +
  geom_col(aes(fill = key))

enter image description here

solved Stacked bar chart in R [closed]