【问题标题】:ggplot2 stacked bars, 2 bars per X variableggplot2 堆积条形图,每个 X 变量 2 个条形图
【发布时间】:2019-11-28 23:01:50
【问题描述】:

假设我有 2 个科目。每个人都做了实验试验和对照试验,两组试验的结果都是 1 或 0。

我想要一个堆积条形图,显示每个受试者在两种类型的试验中 1 响应和 0 响应的比例。

因此,每个主题都会有两个条形,它们在 y 轴上的比例都达到 1.00。

模拟数据

df1 <- data.frame(Sbj_ID = c(1),
              Trial_Type = c("Testing", "Testing", "Control", "Control"),
              Outcome = c(1, 0, 1, 0),
              Proportion = c(0.41, 0.59, 0.02, 0.98))

df2 <- data.frame(Sbj_ID = c(2),
              Trial_Type = c("Testing", "Testing", "Control", "Control"),
              Outcome = c(1, 0, 1, 0),
              Proportion = c(0.30, 0.70, 0.10, 0.90))

df <- merge(df1, df2, all=TRUE)

我希望它看起来像这种类型的图形,但带有堆叠的条形

data(iris)
library(ggplot2)
library(tidyr)

iris %>%
  gather("Type", "Value",-Species) %>%
  ggplot(aes(Species, Value, fill = Type)) +
  geom_bar(position = "dodge", stat = "identity") 

这是我失败的尝试......

library(ggplot2)
library(tidyr)

# fail 1 
 df $>$
   gather("Outcome", "Proportion", -Sbj_ID) %>%
   ggplot(aes(Sbj_ID, Proporiton, fill = Outcome)) +
   geom_bar(stat = "identity", position = "dodge")

# fail 2 
 ggplot(df, aes( x = factor(Sbj_ID), y = Proportion, fill = Outcome)) +
   geom_bar(stat = "identity", position = "stack") 

有什么想法吗?提前谢谢!

【问题讨论】:

    标签: r ggplot2 geom-bar


    【解决方案1】:

    这就是我要做的 -

    • 将 Outcome 和 Sbj_ID 转换为因子变量
    • 使用 facet_wrap 按 Sbj_ID 分组

    您正试图沿着 Outcome “堆叠”,但沿着 Sbj_ID “躲避”。因此,使用 facet_wrap 处理 Sbj_ID 允许您只使用“堆栈”作为结果。

    df  %>% 
     mutate(Outcome = as.factor(Outcome)) %>% 
     ggplot(aes(x = Trial_Type, y = Proportion, fill = Outcome)) + 
     geom_bar(stat = "identity", position = 'stack') +
     facet_wrap(vars(Sbj_ID))
    

    See the output here

    【讨论】:

      【解决方案2】:

      我的直接建议是删除 position = "dodge" 参数。然后ggplot2 将使用频率计数堆叠条形,如下所示。

      iris %>%
          gather("Type", "Value",-Species) %>%
          ggplot(aes(Species, Value, fill = Type)) +
          geom_bar(stat = "identity") 
      

      如果您想确保堆叠的条形图等于 1,可以将参数 position=position_fill(reverse=F) 添加到 geom_bar() 函数。

      iris %>%
          gather("Type", "Value",-Species) %>%
          ggplot(aes(Species, Value, fill = Type)) +
          geom_bar(stat = "identity",position=position_fill(reverse=F)) 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多