[英]R: ggplot2 Barplot for binomial outcome
我想用 ggplot2 创建一个条形图,绘制二项式结果的百分比。 这是我拥有的数据:
IndividualID Pass Group
001 Yes Group1
002 Yes Group1
003 No Group1
004 Yes Group2
005 No Group2
006 No Group2
007 Yes Group3
008 Yes Group3
009 Yes Group3
理想情况下,我想创建类似于此图的内容(从不同的数据集创建):
编辑:我尝试了以下但没有运气。
p<-ggplot(data=data, aes(x=Group, y=Pass)) +
geom_bar(stat="identity", position = 'fill', fill="steelblue")+
scale_y_continuous(labels = scales::percent)
在 ggplot 中必须有一种直接的方法来做到这一点,但这里有一种在绘图前准备数据的方法。
library(dplyr)
library(ggplot2)
df %>%
count(Group, Pass) %>%
group_by(Group) %>%
mutate(n = n/sum(n) * 100) %>%
ggplot() + aes(Group, n, fill = Pass, label = paste0(round(n, 2), "%")) +
geom_col() +
geom_text(position=position_stack(0.5))
数据
df <- structure(list(IndividualID = 1:9, Pass = structure(c(2L, 2L,
1L, 2L, 1L, 1L, 2L, 2L, 2L), .Label = c("No", "Yes"), class = "factor"),
Group = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L), .Label = c("Group1",
"Group2", "Group3"), class = "factor")), class = "data.frame",row.names = c(NA,-9L))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.