交互作用プロット

2要因の群平均を 95% 信頼区間とともに描き、二元配置分散分析を添えます。

交互作用プロット

交互作用プロットは、2つの要因のすべての組み合わせについてアウトカムの平均を示します。一方の要因をx軸に、もう一方を少しずらした色付きの線で表し、各平均には 95% 信頼区間を付けています。線が平行なら2つの要因は独立に作用しており、線が収束・発散・交差する場合は交互作用があることを示します。

舞台は de Marcellis-Warin, Marty, Thelisson & Warin(2022、AI and Ethics)による、人工知能と消費者操作に関する論文です。ここでの数値は説明のために シミュレーション したもの——n = 480 人の消費者について、年齢層とデジタルリテラシーの高低別(各セル60人)に、1〜7 の操作されやすさスコア——であり、論文のデータや結果ではありません。二元配置分散分析(タイプ II 平方和)は statsmodels.formula.api.ols と statsmodels.stats.anova.anova_lm によるもので、各項に偏 η² を添えています。区間は t 分布を用いています。

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

means-with-ci.py · 60 行
ダウンロード GitHub
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
from scipy import stats
from statsmodels.stats.anova import anova_lm

# Simulated data, set in the context of de Marcellis-Warin et al. (2022) [dmw2022manip]

# Data: susceptibility score (1–7) by age group and digital literacy, 60 consumers per cell
rng = np.random.default_rng(2022)
classes = ["18–29", "30–44", "45–59", "60+"]
df = pd.DataFrame([(a, lit) for a in range(4) for lit in ["High", "Low"] for _ in range(60)],
                  columns=["age", "literacy"])
low = (df.literacy == "Low").to_numpy()
df["score"] = np.clip(3.4 + 0.15 * df.age + low * (0.3 + 0.35 * df.age)
                      + rng.normal(0, 1.0, len(df)), 1, 7)
df["age_group"] = pd.Categorical(np.array(classes)[df.age], classes)

# Two-way ANOVA with interaction (type II) + partial eta squared
aov = anova_lm(smf.ols("score ~ C(age_group) * C(literacy)", data=df).fit(), typ=2)
ss_res = aov.loc["Residual", "sum_sq"]
aov["eta_p"] = aov.sum_sq / (aov.sum_sq + ss_res)
df_res = int(aov.loc["Residual", "df"])

# Means and t-based 95% CIs per cell
cells = df.groupby(["literacy", "age_group"], observed=True).score.agg(["mean", "sem", "count"])
cells["half"] = cells["sem"] * stats.t.ppf(0.975, cells["count"] - 1)

fig, ax = plt.subplots(figsize=(8, 5))
x = np.arange(len(classes))
for (lit, c, dx) in [("High", "#007AFF", -0.06), ("Low", "#FF3B30", 0.06)]:
    m = cells.loc[lit].reindex(classes)
    ax.errorbar(x + dx, m["mean"], yerr=m["half"], color=c, lw=2, capsize=0,
                elinewidth=2, marker="o", ms=9, mec="white", mew=1.8)
    ax.annotate(f"{lit} digital\nliteracy", (x[-1] + dx, m["mean"].iloc[-1]), xytext=(14, 0),
                textcoords="offset points", va="center", fontsize=10.5,
                fontweight="semibold", color=c)

ax.set_xticks(x, classes)
ax.set_xlim(-0.3, len(classes) - 0.3)
ax.set_xlabel("Age group (60 consumers per literacy level in each group)")
ax.set_ylabel("Susceptibility to manipulation\n(1–7 score; mean ± 95% CI)")

# One "F(df1, df2) = …, p …, η²p = …" string per ANOVA term
stat = {}
for term, label in [("C(age_group)", "age"), ("C(literacy)", "literacy"),
                    ("C(age_group):C(literacy)", "age × literacy")]:
    r = aov.loc[term]
    pval = "< .001" if r["PR(>F)"] < .001 else f"= {r['PR(>F)']:.2f}"
    stat[label] = f"{label} F({r.df:.0f}, {df_res}) = {r.F:.1f}, p {pval}, η²p = {r.eta_p:.2f}"

gap = cells.loc["Low", "mean"] - cells.loc["High", "mean"]
ax.set_title(f"The literacy gap in susceptibility widens with age, "
             f"from {gap.iloc[0]:.1f} to {gap.iloc[-1]:.1f} points", pad=40)
ax.text(0, 1.075, f"Two-way ANOVA (type II), n = {len(df)} consumers (simulated) · {stat['literacy']}",
        transform=ax.transAxes, fontsize=9.5, color="#6E6E73")
ax.text(0, 1.02, f"{stat['age']} · {stat['age × literacy']}", 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.
  • de Marcellis-Warin et al. (2022), AI and consumer manipulation. de Marcellis-Warin, N., Marty, F., Thelisson, E., & Warin, T. (2022). Artificial intelligence and consumer manipulations: From consumer's counter algorithms to firm's self-regulation tools. AI and Ethics, 2(2), 259–268. https://doi.org/10.1007/s43681-022-00149-5
    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). Interaction plot. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/group-comparisons/means-with-ci/

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

群間比較のその他のグラフ