按组堆叠的比例图

带百分比标签和每组 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 计算。

代码及图中文字均为英文。

stacked-proportions.py · 47 行
下载 GitHub
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()

图表使用了可选的 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}
}

更多比例与问卷调查图表