按组堆叠的比例图
带百分比标签和每组 n 的 100% 堆叠条形图,附卡方检验和 Cramér's V。

ggbarstats() 的 Python 版本。每根条形代表一组并缩放到 100%,因此各段展示的是该组内结局的条件分布;标签为行百分比,每根条形下方的数字为组的样本量。副标题报告 Pearson χ² 独立性检验以及 Cramér's V——将 χ² 缩放到 0–1 范围的效应量。
背景设定为 Sanger 与 Warin(2018,Canadian Journal of Communication)关于 2014 年魁北克选举在 Twitter 上的研究。数据为用于说明的模拟数据,并非论文的数据或结果:2,400 条提及四个政党(PLQ、PQ、CAQ、QS)之一的推文,每条标注为负面、中性或正面。检验由 scipy.stats.chi2_contingency 完成,V 由 scipy.stats.contingency.association 计算。
代码及图中文字均为英文。
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy import stats
from scipy.stats.contingency import association
# Simulated data, set in the context of Sanger & Warin (2018) [sanger2018quebec]
# Simulated tweets: party mentioned and sentiment, with party-specific sentiment shares
rng = np.random.default_rng(2014)
probs = {"PLQ": [0.38, 0.37, 0.25], "PQ": [0.47, 0.33, 0.20],
"CAQ": [0.33, 0.42, 0.25], "QS": [0.24, 0.40, 0.36]}
sizes = {"PLQ": 820, "PQ": 900, "CAQ": 420, "QS": 260}
df = pd.DataFrame([(p, s) for p, n in sizes.items()
for s in rng.choice(["Negative", "Neutral", "Positive"], n, p=probs[p])],
columns=["party", "sentiment"])
table = pd.crosstab(pd.Categorical(df.party, list(sizes)), df.sentiment)
pct = table.div(table.sum(axis=1), axis=0) * 100
# Pearson chi-squared test of independence + Cramér's V
chi2, p, dof, _ = stats.chi2_contingency(table, correction=False)
v = association(table.to_numpy(), method="cramer")
fig, ax = plt.subplots(figsize=(8, 5.2))
colors = ["#FF3B30", "#C7C7CC", "#007AFF"]
x = np.arange(len(pct))
bottom = np.zeros(len(pct))
for sent, c in zip(pct.columns, colors):
ax.bar(x, pct[sent], bottom=bottom, color=c, width=0.68, label=sent, edgecolor="white", lw=1)
for xi, (b, h) in enumerate(zip(bottom, pct[sent])):
ax.text(xi, b + h / 2, f"{h:.0f}%", ha="center", va="center", fontsize=10.5,
fontweight="semibold", color="#1D1D1F" if c == "#C7C7CC" else "white")
bottom += pct[sent].to_numpy()
ax.set_xticks(x, [f"{g}\n(n = {n:,} tweets)" for g, n in zip(pct.index, table.sum(axis=1))])
ax.set_yticks(range(0, 101, 25), [f"{t}%" for t in range(0, 101, 25)])
ax.set_ylim(0, 100)
ax.grid(False)
ax.spines["left"].set_visible(False)
ax.legend(ncols=3, loc="lower left", bbox_to_anchor=(0, 1.0), fontsize=9.5,
handlelength=1, borderaxespad=0.3)
ax.set_title("Sentiment shares by party, with a χ² test of independence", pad=46)
p_txt = "p < .001" if p < 0.001 else f"p = {p:.3f}"
ax.text(0, 1.105, f"Pearson χ²({dof}) = {chi2:.1f}, {p_txt}, Cramér's V = {v:.2f} · "
f"n = {table.to_numpy().sum():,} tweets (simulated)", transform=ax.transAxes,
fontsize=9.5, color="#6E6E73")
plt.show()
# Stacked proportions by group: the R equivalent of plot.py
# Simulated data, set in the context of Sanger & Warin (2018) [sanger2018quebec]
# R and NumPy draw different random numbers, so the values differ slightly from the Python figure.
library(ggplot2)
set.seed(2014)
# Simulated tweets: party mentioned and sentiment, with party-specific sentiment shares
sentiments <- c("Negative", "Neutral", "Positive")
probs <- list(PLQ = c(0.38, 0.37, 0.25), PQ = c(0.47, 0.33, 0.20),
CAQ = c(0.33, 0.42, 0.25), QS = c(0.24, 0.40, 0.36))
sizes <- c(PLQ = 820, PQ = 900, CAQ = 420, QS = 260)
d <- do.call(rbind, lapply(names(sizes), function(party)
data.frame(party = party, sentiment = sample(sentiments, sizes[[party]], replace = TRUE,
prob = probs[[party]]))))
d$party <- factor(d$party, levels = names(sizes))
d$sentiment <- factor(d$sentiment, levels = sentiments)
# Pearson chi-squared test of independence + Cramér's V
tab <- table(d$party, d$sentiment)
chi <- chisq.test(tab, correct = FALSE)
v <- sqrt(unname(chi$statistic) / (sum(tab) * (min(dim(tab)) - 1)))
# Row percentages: the conditional distribution of sentiment within each party
pct <- as.data.frame(prop.table(tab, 1) * 100, responseName = "share")
names(pct)[1:2] <- c("party", "sentiment")
pct$sentiment <- factor(pct$sentiment, levels = rev(sentiments)) # negative at the bottom of the bar
p <- ggplot(pct, aes(party, share, fill = sentiment)) +
geom_col(width = 0.68, colour = "white", linewidth = 0.5) +
geom_text(aes(label = sprintf("%.0f%%", share), colour = sentiment == "Neutral", group = sentiment),
position = position_stack(vjust = 0.5), fontface = "bold", size = 3.7,
show.legend = FALSE) +
scale_colour_manual(values = c(`TRUE` = "#1D1D1F", `FALSE` = "white")) +
scale_fill_manual(NULL, values = c(Negative = "#FF3B30", Neutral = "#C7C7CC", Positive = "#007AFF"),
breaks = sentiments) +
scale_x_discrete(labels = sprintf("%s\n(n = %s tweets)", names(sizes),
format(rowSums(tab), big.mark = ","))) +
scale_y_continuous(breaks = seq(0, 100, 25), labels = function(b) paste0(b, "%"),
expand = c(0, 0)) +
labs(title = "Sentiment shares by party, with a χ² test of independence",
subtitle = sprintf("Pearson χ²(%d) = %.1f, %s, Cramér's V = %.2f · n = %s tweets (simulated)",
chi$parameter, chi$statistic,
if (chi$p.value < .001) "p < .001" else sprintf("p = %.3f", chi$p.value),
v, format(sum(tab), big.mark = ",")),
x = NULL, 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.x = element_text(colour = "#1D1D1F", size = 10),
panel.grid = element_blank(),
legend.position = "top", legend.justification = "left",
legend.key.size = unit(0.8, "lines"), legend.text = element_text(size = 9.5),
legend.margin = margin(0, 0, 0, 0))
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. - Sanger & Warin (2018), the 2014 Québec election on Twitter. Sanger, W., & Warin, T. (2018). The public's perception of political parties during the 2014 Québec election on Twitter. Canadian Journal of Communication, 43(2), 245–263. https://doi.org/10.22230/cjc.2018v43n2a3251
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). Stacked proportions by group. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/proportions-surveys/stacked-proportions/
@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}
}