简体   繁体   中英

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:

在此处输入图像描述

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:

在此处输入图像描述

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.

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM