標準化残差付きクロス集計表

分割表をヒートマップとして描き、独立性からの標準化残差で色分けします。

標準化残差付きクロス集計表

ggstats::ggtable() の Python 版です。おなじみのクロス集計表ですが、各セルは 標準化(調整済み)残差、すなわち観測度数が独立性の仮定のもとでの予測値から標準誤差いくつ分上下にずれているかによって色分けされています。独立性のもとではこれらの残差はほぼ標準正規分布に従うため、±2 を超えるセル(太字で表示)が χ² 検定を有意にしているセルです。各セルには度数と行パーセントを表示し、周辺には合計を示しています。

設定は Kouloukoui, de Marcellis-Warin, Gomes & Warin (2023, Journal of Cleaner Production) による、ESG をテーマとする Twitter 上の会話の研究です。データは説明のための シミュレーション であり、論文のデータや結果では ありません。4,000 件のツイートそれぞれに、ESG のサブテーマと投稿者の地域を割り当てています。期待度数は scipy.stats.chi2_contingency で求め、残差は (O − E) / √(E · (1 − 行の割合) · (1 − 列の割合)) で計算しています。

コードおよび図中のテキストは英語です。

crosstab-residuals.py · 61 行
ダウンロード GitHub
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.colors import TwoSlopeNorm
from scipy import stats
# Simulated data, set in the context of Kouloukoui et al. (2023) [kouloukoui2023esg]

# Simulated tweets: ESG sub-topic (rows) × world region (columns), topic mix varies by region
rng = np.random.default_rng(2023)
topics = ["E · Climate change", "E · Pollution & waste", "S · Labour & human rights",
          "S · Diversity & inclusion", "G · Board & executive pay", "G · Corruption & ethics"]
mix = {"North America": ([.30, .10, .12, .22, .18, .08], 1400), "Europe": ([.38, .14, .12, .14, .14, .08], 1200),
       "Asia-Pacific": ([.28, .24, .14, .10, .14, .10], 800), "Latin America": ([.24, .16, .20, .10, .08, .22], 350),
       "Africa": ([.22, .14, .24, .10, .08, .22], 250)}
df = pd.DataFrame([(t, r) for r, (pr, n) in mix.items() for t in rng.choice(topics, n, p=pr)],
                  columns=["topic", "region"])
table = pd.crosstab(pd.Categorical(df.topic, topics), pd.Categorical(df.region, list(mix)))
obs = table.to_numpy()
n = obs.sum()

# Chi-squared test and adjusted (standardized) residuals
chi2, p, dof, exp = stats.chi2_contingency(obs, correction=False)
row_share, col_share = obs.sum(1, keepdims=True) / n, obs.sum(0, keepdims=True) / n
std_resid = (obs - exp) / np.sqrt(exp * (1 - row_share) * (1 - col_share))
row_pct = obs / obs.sum(1, keepdims=True) * 100
v = np.sqrt(chi2 / (n * (min(obs.shape) - 1)))

fig, ax = plt.subplots(figsize=(9, 5))
norm = TwoSlopeNorm(0, vmin=-6, vmax=6)
im = ax.imshow(std_resid, cmap="RdBu", norm=norm, aspect="auto")
for i in range(obs.shape[0]):
    for j in range(obs.shape[1]):
        strong = abs(std_resid[i, j]) >= 2
        ax.text(j, i - 0.12, f"{obs[i, j]:,}", ha="center", va="center", fontsize=11,
                fontweight="bold" if strong else "normal",
                color="white" if abs(std_resid[i, j]) > 3 else "#1D1D1F")
        ax.text(j, i + 0.2, f"{row_pct[i, j]:.0f}%", ha="center", va="center", fontsize=8.5,
                color="white" if abs(std_resid[i, j]) > 3 else "#3A3A3C")

# White gutters between cells and totals in the margins
ax.set_xticks(np.arange(-0.5, obs.shape[1]), minor=True)
ax.set_yticks(np.arange(-0.5, obs.shape[0]), minor=True)
ax.grid(which="minor", color="white", lw=3)
ax.grid(which="major", visible=False)
ax.tick_params(which="minor", length=0)
regions = [c.replace(" ", "\n") for c in table.columns]          # two-word regions on two lines
ax.set_xticks(range(obs.shape[1]), [f"{c}\n(n = {t:,})" for c, t in zip(regions, obs.sum(0))])
ax.set_yticks(range(obs.shape[0]), [f"{r}  (n = {t:,})" for r, t in zip(table.index, obs.sum(1))])
for s in ax.spines.values():
    s.set_visible(False)
ax.set_xlabel("World region of the tweet")
ax.set_ylabel("ESG sub-topic")

cb = fig.colorbar(im, ax=ax, shrink=0.85, pad=0.02, ticks=[-6, -4, -2, 0, 2, 4, 6])
cb.set_label("Standardized residual", color="#3A3A3C")
cb.outline.set_visible(False)
ax.set_title("Each region tweets about a different side of ESG", pad=26)
ax.text(0, 1.02, f"Pearson χ²({dof}) = {chi2:.0f}, p < .001, V = {v:.2f} · n = {n:,} tweets (simulated) · "
        "count & row % · bold: |resid.| ≥ 2", 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.
  • Kouloukoui et al. (2023), global conversations on ESG topics. Kouloukoui, D., de Marcellis-Warin, N., Gomes, S. M. S., & Warin, T. (2023). Mapping global conversations on twitter about environmental, social, and governance topics through natural language processing. Journal of Cleaner Production, 414, 137369. https://doi.org/10.1016/j.jclepro.2023.137369
    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). Cross-table with standardized residuals. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/proportions-surveys/crosstab-residuals/

@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}
}

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