-5

I have a data set that looks like this

enter image description here

I want to plot a stacked bar chart with X being Session and Y as Absent and Present stacked one above another. How to do this in ggplot() in R

Manoj
  • 101
  • 2
  • 9
  • 2
    And your code attempt is where? – Maurits Evers Apr 13 '18 at 01:34
  • 2
    Welcome to stackoverflow. Please refer to `ggplot` documentation https://ggplot2.tidyverse.org/. Please try to make a minimal attempt to solve your issue... – Matias Andina Apr 13 '18 at 01:35
  • 1
    Possible duplicate of [Plotting a stacked bar plot?](https://stackoverflow.com/questions/12592041/plotting-a-stacked-bar-plot) – Cristian E. Nuno Apr 13 '18 at 02:33
  • I'm sorry I did try various methods like this `p <- ggplot(out, aes(Session)) + geom_bar() + geom_bar(aes(weight= Present)) + geom_bar (aes(fill= Absent))` but I was not getting it. I thought one who answers it will give a completely new answers. and no point in pasting my non working code. – Manoj Apr 13 '18 at 15:11

1 Answers1

2

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

Dom
  • 1,043
  • 2
  • 10
  • 20