带置信区间的比例
按大小排序的比例点图,附 Wilson 95% 置信区间。

当问题是“每组中有多大比例……?”时,每组一个点加上其置信区间,胜过条形图:眼睛比较的是位置,而区间宽度能立刻显示每个比例的精确程度。这里使用 Wilson 得分区间而非教科书中的 Wald 区间,因为前者在小样本以及比例接近 0 或 1 时仍能保持 95% 的覆盖率。虚线为各要素的平均比例。
背景设定为 Kouloukoui、de Marcellis-Warin 与 Warin(2025,Climate)关于企业气候转型计划的研究。数据为用于说明的模拟数据,并非论文的数据或结果:240 家企业,逐一编码其计划是否包含七个要素(目标、资本支出、治理、范围 3 等)。区间由 statsmodels.stats.proportion.proportion_confint(method="wilson") 计算。由于每家企业都在每个要素上编码,七个比例是否相等用 Cochran Q 检验(statsmodels.stats.contingency_tables.cochrans_q)检验。
代码及图中文字均为英文。
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from statsmodels.stats.contingency_tables import cochrans_q
from statsmodels.stats.proportion import proportion_confint
# Simulated data, set in the context of Kouloukoui, de Marcellis-Warin & Warin (2025) [kouloukoui2025climate]
# Simulated coding: 240 firms × 7 plan elements (1 = included), linked by a firm-level ambition
rng = np.random.default_rng(88)
elements = {"Emission-reduction targets": 1.3, "Board oversight of climate": 0.7,
"Interim (2030) milestones": 0.2, "Capex aligned with the plan": -0.6,
"Scope 3 emissions covered": -0.9, "Executive pay linked to climate": -1.3,
"Just-transition measures": -1.9}
ambition = rng.normal(0, 1, 240)
plans = pd.DataFrame({e: (b + ambition + rng.normal(0, 1, 240) > 0).astype(int)
for e, b in elements.items()})
# Proportion + Wilson 95% CI per element, sorted
g = pd.DataFrame({"k": plans.sum(), "n": len(plans)})
g["p"] = g.k / g.n
g["low"], g["high"] = proportion_confint(g.k, g.n, alpha=0.05, method="wilson")
g = g.sort_values("p")
# Cochran's Q: do the seven elements appear equally often in the same firms' plans?
q = cochrans_q(plans.to_numpy())
overall = g.p.mean()
fig, ax = plt.subplots(figsize=(8, 4.8))
y = np.arange(len(g))
ax.axvline(overall, color="#8E8E93", lw=1, ls="--", zorder=1)
ax.text(overall, len(g) - 0.45, f" average {overall:.0%}", fontsize=9, color="#6E6E73", va="bottom")
ax.hlines(y, g.low, g.high, color="#007AFF", lw=2.5, alpha=0.45, zorder=2)
ax.scatter(g.p, y, s=80, color="#007AFF", edgecolor="white", lw=1.5, zorder=3)
for yi, (_, row) in zip(y, g.iterrows()):
ax.text(1.04, yi, f"{row.p:.0%}", va="center", fontsize=10, fontweight="semibold", color="#007AFF")
ax.text(1.12, yi, f"{row.k:.0f} / {row.n:.0f}", va="center", fontsize=9.5, color="#6E6E73")
ax.set_yticks(y, g.index)
ax.set_ylim(-0.6, len(g) - 0.2)
ax.set_xlim(0, 1.26)
ax.set_xticks(np.arange(0, 1.01, 0.2))
ax.xaxis.set_major_formatter(plt.matplotlib.ticker.PercentFormatter(1, decimals=0))
ax.grid(axis="x"); ax.grid(axis="y", visible=False)
ax.set_xlabel("Firms whose transition plan includes the element (Wilson 95% CI)")
ax.set_title("Targets are common in transition plans; just-transition measures are rare", pad=26)
ax.text(0, 1.02, f"Cochran's Q({len(g) - 1}) = {q.statistic:.0f}, p < .001 for equal shares · "
f"n = {len(plans)} firms (simulated)", transform=ax.transAxes, fontsize=9.5, color="#6E6E73")
plt.show()
# Proportions with confidence intervals: the R equivalent of plot.py
# Simulated data, set in the context of Kouloukoui, de Marcellis-Warin & Warin (2025) [kouloukoui2025climate]
# R and NumPy draw different random numbers, so the values differ slightly from the Python figure.
library(ggplot2)
set.seed(88)
# Simulated coding: 240 firms × 7 plan elements (1 = included), linked by a firm-level ambition
elements <- c("Emission-reduction targets" = 1.3, "Board oversight of climate" = 0.7,
"Interim (2030) milestones" = 0.2, "Capex aligned with the plan" = -0.6,
"Scope 3 emissions covered" = -0.9, "Executive pay linked to climate" = -1.3,
"Just-transition measures" = -1.9)
n <- 240
ambition <- rnorm(n)
plans <- sapply(elements, function(b) as.integer(b + ambition + rnorm(n) > 0))
# Proportion + Wilson 95% CI per element (prop.test without continuity correction), sorted
g <- data.frame(element = names(elements), k = colSums(plans), n = n)
g$p <- g$k / g$n
ci <- t(mapply(function(k, n) prop.test(k, n, correct = FALSE)$conf.int, g$k, g$n))
g$low <- ci[, 1]
g$high <- ci[, 2]
g$element <- reorder(g$element, g$p)
# Cochran's Q: do the seven elements appear equally often in the same firms' plans?
m <- ncol(plans)
Q <- (m - 1) * (m * sum(colSums(plans)^2) - sum(plans)^2) / (m * sum(plans) - sum(rowSums(plans)^2))
p_q <- pchisq(Q, m - 1, lower.tail = FALSE)
overall <- mean(g$p)
p <- ggplot(g, aes(p, element)) +
geom_vline(xintercept = overall, colour = "#8E8E93", linewidth = 0.45, linetype = "dashed") +
annotate("text", x = overall, y = m + 0.62, label = sprintf(" average %.0f%%", 100 * overall),
hjust = 0, size = 3.1, colour = "#6E6E73") +
geom_linerange(aes(xmin = low, xmax = high), colour = "#007AFF", linewidth = 1.2, alpha = 0.45) +
geom_point(shape = 21, size = 3.8, fill = "#007AFF", colour = "white", stroke = 1) +
geom_text(aes(x = 1.04, label = sprintf("%.0f%%", 100 * p)), hjust = 0, size = 3.5,
fontface = "bold", colour = "#007AFF") +
geom_text(aes(x = 1.12, label = sprintf("%d / %d", k, n)), hjust = 0, size = 3.3,
colour = "#6E6E73") +
scale_x_continuous(breaks = seq(0, 1, 0.2), labels = scales::percent, limits = c(0, 1.26),
expand = c(0, 0)) +
scale_y_discrete(expand = expansion(add = c(0.6, 0.9))) +
labs(title = "Targets are common in transition plans; just-transition measures are rare",
subtitle = sprintf("Cochran's Q(%d) = %.0f, %s for equal shares · n = %d firms (simulated)",
m - 1, Q, if (p_q < .001) "p < .001" else sprintf("p = %.3f", p_q), n),
x = "Firms whose transition plan includes the element (Wilson 95% CI)", y = NULL) +
theme_minimal(base_size = 11) +
theme(plot.title = element_text(face = "bold"),
plot.title.position = "plot",
plot.subtitle = element_text(size = 8.5, colour = "#6E6E73"),
axis.text.y = element_text(colour = "#1D1D1F", size = 10),
panel.grid.minor = element_blank(), panel.grid.major.y = element_blank())
print(p)
图表使用了可选的 PyStatlas 样式:添加 plt.style.use("pystatlas.mplstyle") 即可完全还原其外观。
数据来源
- Simulated data. Simulated data with a fixed random seed, created for this example.
No real respondents, documents or measurements: the numbers only illustrate how the chart and its statistics work. - Kouloukoui, de Marcellis-Warin & Warin (2025), corporate climate transition plans. Kouloukoui, D., de Marcellis-Warin, N., & Warin, T. (2025). Barriers, opportunities and best practices for corporate climate transition plans: A literature review. Climate, 13(5), 88. https://doi.org/10.3390/cli13050088
The example is set in the context of this paper; unless its description says otherwise, the numbers are simulated and are not the paper's data or results.
这些示例用于说明统计方法。除条目另有说明外,其数值均为模拟数据,图表标题描述的是该图在这些模拟数据中呈现的内容——既不是所引论文的结论,也不是作者对实质问题的立场。关于结果、背景和数据,请以此处引用的论文为准。
如何引用
PyStatlas 由 Thierry Warin 创建并维护。如果它对你的工作有所帮助,敬请引用。
Warin, T. (2026). Proportions with confidence intervals. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/proportions-surveys/proportions-with-ci/
@misc{warin2026statlas,
author = {Warin, Thierry},
title = {PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences},
year = {2026},
version = {1.1.0},
howpublished = {\url{https://warin.ca/pystatlas/}},
note = {Source code: https://github.com/warint/pystatlas}
}