ピアソン残差付きモザイクプロット

セル度数に比例した面積のタイルを、独立性からのピアソン残差で色分けします。

ピアソン残差付きモザイクプロット

モザイクプロットは、二元表を正方形をタイルに分割した形で描きます。列の 幅 は第1変数の周辺割合、タイルの 高さ は第2変数の条件付き割合を表すため、各タイルの面積は度数に比例します。vcd::mosaic(shade = TRUE) と同様に、色は ピアソン残差 (observed − expected) / √expected を表します。青いタイルは独立性から予測されるよりツイートが多く、赤いタイルは少ないことを示し、±2 や ±4 を超える残差は χ² を押し上げているセルを示します。

設定は Stojkov & Warin (2023, Discourse & Communication) による、ヨーロッパの難民危機をめぐる Twitter 上の言説の研究です。データは説明のための シミュレーション であり、論文のデータや結果では ありません。難民に関する 3,000 件のツイートそれぞれに、発信国と主要な言説フレーム(人道、安全保障、経済、政治)を割り当てています。タイルは ax.bar で手作業で描き、期待度数は scipy.stats.chi2_contingency で求めています。

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

mosaic-plot.py · 60 行
ダウンロード 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 Stojkov & Warin (2023) [stojkov2023refugee]

# Simulated tweets: country of origin × dominant discourse frame, frame shares vary by country
rng = np.random.default_rng(2015)
frames = ["Humanitarian", "Security", "Economic", "Political"]
mix = {"Germany": ([0.46, 0.18, 0.18, 0.18], 1000), "UK": ([0.30, 0.26, 0.26, 0.18], 700),
       "France": ([0.36, 0.26, 0.14, 0.24], 550), "Italy": ([0.32, 0.22, 0.16, 0.30], 450),
       "Hungary": ([0.16, 0.44, 0.10, 0.30], 300)}
df = pd.DataFrame([(c, f) for c, (pr, n) in mix.items() for f in rng.choice(frames, n, p=pr)],
                  columns=["country", "frame"])
table = pd.crosstab(pd.Categorical(df.country, list(mix)), pd.Categorical(df.frame, frames))
obs = table.to_numpy()

# Chi-squared test and Pearson residuals
chi2, p, dof, expected = stats.chi2_contingency(obs, correction=False)
resid = (obs - expected) / np.sqrt(expected)

fig, ax = plt.subplots(figsize=(8.5, 5.6))
cmap = plt.get_cmap("RdBu")                         # red = fewer than expected, blue = more
norm = TwoSlopeNorm(0, vmin=-8, vmax=8)
gap = 0.012
widths = obs.sum(axis=1) / obs.sum()
x0 = 0
for i, w in enumerate(widths):
    heights = obs[i] / obs[i].sum()
    y0 = 0
    for j, h in enumerate(heights):
        ax.bar(x0, h - gap, width=w - gap, bottom=y0, align="edge",
               color=cmap(norm(resid[i, j])), edgecolor="none")
        sep = "  " if h < 0.12 else "\n"              # thin tiles get a one-line label
        ax.text(x0 + (w - gap) / 2, y0 + (h - gap) / 2, f"{obs[i, j]}{sep}{resid[i, j].round(1) + 0:+.1f}", ha="center", va="center",
                fontsize=9, linespacing=1.3, color="white" if abs(resid[i, j]) > 5 else "#1D1D1F")
        y0 += h
    ax.text(x0 + (w - gap) / 2, -0.03, f"{table.index[i]}\n(n = {obs[i].sum()})", ha="center", va="top",
            fontsize=10, color="#3A3A3C")
    x0 += w

# Row labels on the left, placed at the heights of the first column
y0 = 0
for j, h in enumerate(obs[0] / obs[0].sum()):
    ax.text(-0.015, y0 + (h - gap) / 2, table.columns[j], ha="right", va="center", fontsize=10, color="#3A3A3C")
    y0 += h

sm_ = plt.cm.ScalarMappable(norm=norm, cmap=cmap)
cb = fig.colorbar(sm_, ax=ax, shrink=0.8, pad=0.02, ticks=[-8, -4, 0, 4, 8])
cb.set_label("Pearson residual", color="#3A3A3C")
cb.outline.set_visible(False)
ax.set_xlim(0, 1 - gap); ax.set_ylim(0, 1 - gap)
ax.axis("off")
ax.text(0.5, -0.15, "Country of the tweet", transform=ax.transAxes, ha="center", fontsize=11)
ax.text(-0.19, 0.5, "Discourse frame", transform=ax.transAxes, rotation=90, va="center", fontsize=11)
ax.set_title("The mix of refugee frames changes from one country to the next", pad=26)
ax.text(0, 1.02, f"Pearson χ²({dof}) = {chi2:.0f}, p < .001 · n = {obs.sum():,} tweets (simulated) · "
        "tile labels: count and residual", 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.
  • Stojkov & Warin (2023), the refugee crisis on Twitter. Stojkov, A., & Warin, T. (2023). Discursive dynamics and local contexts on Twitter: The refugee crisis in Europe. Discourse & Communication, 17(3), 354–380. https://doi.org/10.1177/17504813231155739
    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). Mosaic plot with Pearson 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/mosaic-plot/

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

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