Search code examples
rggplot2geom-bar

Create multiple bar graphs in one bar graph


I have a dataset which looks like the following:

my_DataSet <- {
# Variable A Variable B Variable C Control Group
1 1 0 0 1
2 1 1 0 1
3 0 0 1 0
}

Following Plot multiple boxplot in one graph, I did a transformation (new_DataSet <- melt(my_DataSet, id.var = "Control_Group")) so that the resulting data looks like this: I have a dataset which looks like the following:

new_DataSet <- {
# Control Group variable value
1 1 Variable A 1
2 1 Variable B 0
3 1 Variable C 0
4 1 Variable A 1
5 1 Variable B 1
6 1 Variable C 0
7 0 Variable A 0
8 0 Variable B 0
9 0 Variable C 1
}

I want to produce a bar graph which shows the percentage of 1s in the control and intervention group along all 3 variables.

I imagine something like the following bar graph:

enter image description here

What I have done is the following:

p <- ggplot(data = my_DataSet)
p + geom_bar(mapping = aes(x = Variable_A, y = ..prop.., fill = Control_Group), position = "dodge")

This results in:

enter image description here

Which has two issues

  • It only displays Variable A, not A, B and C
  • I only want the percentage for the 1s, not for the zeroes. If I filter my data beforehand, the proportion becomes wrong, however.

Solution

  • You can get the proportions for each column and each control group and plot the bar graph.

    library(tidyverse)
    
    my_DataSet %>%
      pivot_longer(cols = -Control_group) %>%
      group_by(name, Control_group = recode(Control_group, 
                     '1' = 'control', '0' = 'intervention')) %>%
      summarise(value = mean(value)) %>%
      ggplot() + aes(name, value, fill = Control_group) + 
      geom_bar(stat = 'identity', position = 'dodge')