【问题标题】:Bar graph for binary variable across two groups?两组二进制变量的条形图?
【发布时间】:2020-10-09 11:22:50
【问题描述】:

我有以下数据(示例如下):

Participant Group  Choice
1           Control     0
2           Control     0
3           Control     0
4           Stress      1
5           Stress      1
6           Stress      1

我想创建一个条形图来描述组(压力 VS 控制)的选择频率(0 或 1)。

【问题讨论】:

    标签: r data-visualization bar-chart


    【解决方案1】:

    创建一个table 并使用R 附带的barplot

    barplot(with(dat, table(Choice, Group)), main="My plot", beside=T, col=2:3)
    


    数据:

    (请原谅我选择了稍微有趣的数据:)

    dat <- structure(list(Participant = 1:6, Group = c("Control", "Control", 
    "Control", "Stress", "Stress", "Stress"), Choice = c(0L, 1L, 
    0L, 0L, 1L, 1L)), class = "data.frame", row.names = c(NA, -6L
    ))
    

    【讨论】:

      【解决方案2】:

      您可以使用count 计算频率,将变量转换为因子并绘图。

      library(dplyr)
      library(ggplot2)
      
      df %>%
        count(Group, Choice) %>%
        mutate(Choice = factor(Choice), Group = factor(Group)) %>%
        ggplot() + aes(Group, n, fill = Choice) + geom_col()
      

      【讨论】:

      • 谢谢 - 我的 Group 变量实际上已经被定义为一个因素。我该如何修改代码?
      • 您可以从mutate 中删除Group = factor(Group) 行。
      • 计数错误(., Group, Info_ChoiceR) : object 'Group' not found
      • @Chester 你的专栏叫Group 吗?你能按原样运行上面的代码吗?这行得通吗?
      • 不,很遗憾,我在整个代码中遇到了麻烦。这些变量在我的回归中有效,但不适用于绘图。