群別の積み上げ割合

割合ラベル、棒ごとの n、カイ二乗検定、クラメールの V を伴う 100% 積み上げ棒グラフ。

群別の積み上げ割合

ggbarstats() の Python 版です。各棒は1つの群を 100% に換算したもので、各区分は群内におけるアウトカムの 条件付き分布 を表します。ラベルは行パーセントで、棒の下の数字は群のサイズです。サブタイトルには、ピアソンの χ² 独立性検定と、χ² を 0–1 の範囲に換算した効果量 クラメールの V を示しています。

設定は Sanger & Warin (2018, Canadian Journal of Communication) による、Twitter 上の 2014年ケベック州選挙の研究です。データは説明のための シミュレーション であり、論文のデータや結果では ありません。4つの政党(PLQ、PQ、CAQ、QS)のいずれかに言及した 2,400 件のツイートに、否定的・中立・肯定的のラベルを付けています。検定は 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}
}

割合と調査データのその他のグラフ