如何正确计算比例表的95%置信区间并使用ggplot2绘制误差棒?
问题:为区域学校比例计算95%置信区间并正确绘制误差棒
我认为95%置信区间(CI)是误差棒最具信息性的选择,希望为A-E各区域的学校数量比例计算该值,并使用ggplot2绘制带误差棒的柱状图。
数据说明:数据包含A-E各区域收集到的学校数量比例。
已尝试的步骤
- 计算比例
region <- data %>% count(Q8) %>% mutate(prop = round((prop.table(n) * 100), digits = 2), sd = round(sd(prop.table(n)), digits = 2), Q8 = fct_reorder(Q8, n)) %>% arrange(n)
输出结果:
> region Q8 n prop sd 1 E 3 10.34 0.12 2 C 3 10.34 0.12 3 B 4 13.79 0.12 4 A 9 31.03 0.12 5 D 10 34.48 0.12
- 尝试计算95% CI
region_ci <- data.frame(DescTools::MultinomCI(region$n, conf.level = 0.95)) %>% mutate_if(is.numeric, round, 2)
输出结果:
> region_ci est lwr.ci upr.ci 1 0.10 0.00 0.29 2 0.10 0.00 0.29 3 0.14 0.00 0.32 4 0.31 0.14 0.49 5 0.34 0.17 0.53
- 尝试绘图
region %>% ggplot(aes(y = prop, x = ordered(Q8), fill = Q8)) + geom_bar(stat = "identity", width = 0.3) + geom_errorbar(aes(ymin= region_ci$lwr.ci, ymax= region_ci$upr.ci, width= .1)) + geom_text(aes(label = round(prop, 1.5)), nudge_y = 2) + # 避免标签与柱子顶部重叠 labs(x = "区域", y = '(%)')
绘图时误差棒显示异常,显然CI计算或绘图环节存在问题,请问如何正确计算95% CI并绘制正确的误差棒?
附region数据的dput结果:
> dput(region) structure(list(Q8 = structure(1:5, .Label = c("E", "C", "B", "A", "D"), class = "factor"), n = c(3L, 3L, 4L, 9L, 10L), prop = c(10.34, 10.34, 13.79, 31.03, 34.48), sd = c(0.12, 0.12, 0.12, 0.12, 0.12 )), row.names = c(NA, -5L), class = "data.frame")
解决方案
问题根源
误差棒异常的核心原因是置信区间与比例的单位不匹配:MultinomCI返回的CI是小数形式(0-1范围),但你的prop是百分比形式(0-100范围),直接使用会导致误差棒长度极小;另外,调用外部数据框region_ci容易出现索引错位问题。
修正步骤
- 重新计算并合并95% CI
将MultinomCI的结果转换为百分比,并合并到主数据框中:
library(tidyverse) library(DescTools) # 计算置信区间并转换为百分比,合并到region region <- region %>% bind_cols( data.frame(MultinomCI(.$n, conf.level = 0.95)) %>% mutate(across(c(est, lwr.ci, upr.ci), ~ .x * 100)) %>% # 转换为百分比 mutate(across(where(is.numeric), round, 2)) )
处理后region会包含百分比形式的置信区间列。
- 绘制正确的带误差棒柱状图
使用合并后的数据,确保误差棒单位与比例一致:
region %>% ggplot(aes(y = prop, x = Q8, fill = Q8)) + geom_bar(stat = "identity", width = 0.3) + # 使用数据框内的百分比置信区间 geom_errorbar(aes(ymin = lwr.ci, ymax = upr.ci), width = .1) + geom_text(aes(label = prop), nudge_y = 2) + labs(x = "区域", y = "学校数量比例 (%)") + theme_minimal()
补充说明
MultinomCI针对多项分布计算置信区间,适合类别比例场景,计算逻辑本身正确,只需统一单位即可。- 将置信区间合并到主数据框后,可避免ggplot调用外部数据时的索引错位问题。
内容的提问来源于stack exchange,提问作者Larissa Cury
相关产品推荐
相关产品推荐

