-1

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.
Narusan
  • 482
  • 1
  • 5
  • 18

1 Answers1

2

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')
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Thanks. It took me some time to get it to work: I had some more stuff in the dataset (Age, Sex etc.) which was logically also moved in the pivot. I had to change the sex from a character into a number (wasn't nice but did the trick). I could remove all other values with `subset(data.frame, logical conditions)` [just left the comment here in case it helps some beginners like me in the future] – Narusan Dec 29 '20 at 14:23