【发布时间】: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")
有什么想法吗?提前谢谢!
【问题讨论】: