追加変数プロット

説明変数ごとの偏回帰パネル。当てはめた各傾きはその回帰係数に一致します。

追加変数プロット

重回帰では、y と1つの説明変数の単純な散布図には、その変数の効果と、それに相関するあらゆるものの効果が混在します。追加変数プロット はこれを取り除きます。y を 他の すべての説明変数に回帰した残差を、注目する説明変数を同じ説明変数に回帰した残差に対してプロットするのです。フリッシュ・ウォー・ロヴェルの定理により、点群を通る直線の傾きは重回帰係数にちょうど一致し、x軸上で遠く離れた点がその係数を左右している点です。

設定は Tengia, Wandschneider, Warin & Wunnava (2011, African Finance Journal) による、南部アフリカの貿易に関する拡張重力モデルの研究です。データは説明のために シミュレーション したもので、論文のデータや結果ではなく、残差診断の例と同じ生成手順によるものです。n = 210 の方向付きペア(アフリカ 15 か国、うち 10 か国が SADC 加盟国)です。輸出額の対数を、輸出国と輸入国の GDP の対数、距離の対数、国境の共有、SADC への共同加盟に statsmodels の smf.ols() で回帰しています。残差は軸ごとに1つの補助的な OLS 当てはめで計算し、各パネルに β、その t 値と p 値を示しています。

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

partial-regression.py · 69 行
ダウンロード GitHub
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
# Simulated data, set in the context of Tengia, Wandschneider, Warin & Wunnava (2011) [tengia2011]

# Data: 15 African economies (10 SADC members), all 210 directed trade pairs
rng = np.random.default_rng(2011)
codes = ["AGO", "BWA", "LSO", "MWI", "MOZ", "NAM", "ZAF", "SWZ", "ZMB", "ZWE",   # SADC
         "KEN", "UGA", "ETH", "NGA", "GHA"]                                       # non-SADC
gdp = rng.normal(23, 1.3, 15)                                    # log GDP (US$)
xy = np.r_[rng.normal([0, -2000], 700, (10, 2)), rng.normal([0, 1500], 1500, (5, 2))]  # km
o, d = np.nonzero(~np.eye(15, dtype=bool))                       # exporter, importer
dist = np.hypot(*(xy[o] - xy[d]).T) + 200
df = pd.DataFrame({"ln_gdp_o": gdp[o], "ln_gdp_d": gdp[d], "ln_dist": np.log(dist),
                   "sadc": ((o < 10) & (d < 10)).astype(int), "border": (dist < 800).astype(int)},
                  index=[f"{codes[a]}-{codes[b]}" for a, b in zip(o, d)])
df["ln_trade"] = (-12 + 0.9 * df.ln_gdp_o + 0.8 * df.ln_gdp_d - 1.2 * df.ln_dist
                  + 0.7 * df.sadc + 0.5 * df.border + rng.standard_t(4, len(df)))

predictors = ["ln_gdp_o", "ln_gdp_d", "ln_dist", "border", "sadc"]
labels = {"ln_gdp_o": "Exporter log GDP", "ln_gdp_d": "Importer log GDP",
          "ln_dist": "Log distance", "border": "Common border (0/1)",
          "sadc": "Both in SADC (0/1)"}
full = smf.ols("ln_trade ~ " + " + ".join(predictors), data=df).fit()

fig, axes = plt.subplots(2, 3, figsize=(11, 7.75), layout="constrained")
fig.get_layout_engine().set(rect=(0, 0, 1, 0.903))   # keep the top of the figure for the title and subtitle
for ax, x in zip(axes.flat, predictors):
    others = " + ".join(p for p in predictors if p != x)
    ey = smf.ols(f"ln_trade ~ {others}", data=df).fit().resid     # y | others
    ex = smf.ols(f"{x} ~ {others}", data=df).fit().resid          # x | others
    sig = full.pvalues[x] < 0.05
    c = "#007AFF" if sig else "#8E8E93"

    ax.axhline(0, color="#E5E5EA", lw=1); ax.axvline(0, color="#E5E5EA", lw=1)
    ax.scatter(ex, ey, s=20, color=c, alpha=0.6, lw=0, zorder=2)
    grid = np.linspace(ex.min(), ex.max(), 2)
    ax.plot(grid, full.params[x] * grid, color="#FF3B30" if sig else "#AEAEB2", lw=2)
    # Label the observation with the most extreme partial x
    for i in np.argsort(-np.abs(ex.to_numpy()))[:1]:
        right = ex.iloc[i] < 0
        ax.annotate(df.index[i], (ex.iloc[i], ey.iloc[i]),
                    xytext=(6 if right else -6, 0), textcoords="offset points",
                    ha="left" if right else "right", va="center", fontsize=8.5, color="#3A3A3C",
                    zorder=3, bbox=dict(boxstyle="round,pad=0.15", fc="white", ec="none", alpha=0.85))
    p = full.pvalues[x]
    ax.set_title(f"β = {full.params[x]:.2f} · t = {full.tvalues[x]:.2f} · "
                 + ("p < .001" if p < .001 else f"p = {p:.3f}"), fontsize=10.5, color=c,
                 fontweight="semibold" if sig else "normal", pad=8)
    ax.set_xlabel(f"{labels[x]} | others", fontsize=10)
    if ax.get_subplotspec().is_first_col():
        ax.set_ylabel("Log exports | others", fontsize=10)
    ax.margins(x=0.12, y=0.15)

# Last cell: reading guide instead of an empty panel
axes.flat[-1].axis("off")
axes.flat[-1].text(0.05, 0.5, "How to read\n\nEach slope is the coefficient of the\n"
                   "full model, net of the other four\npredictors. Red line: p < .05;\n"
                   "grey line: not significant.\nPoints far left or right move\n"
                   "the slope most.", transform=axes.flat[-1].transAxes, va="center",
                   fontsize=10, color="#6E6E73", linespacing=1.5)

fig.text(0.01, 0.962, "Net of the other terms, GDPs, distance and SADC membership shape trade",
         fontsize=15, fontweight="semibold", va="bottom")
fig.text(0.01, 0.921, f"OLS log exports ~ 5 predictors · n = {int(full.nobs)} pairs (simulated) · "
         f"R² = {full.rsquared:.2f} · F({full.df_model:.0f}, {full.df_resid:.0f}) = "
         f"{full.fvalue:.1f}, p < .001", fontsize=9.5, color="#6E6E73", va="bottom")
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.
  • Tengia, Wandschneider, Warin & Wunnava (2011), Southern African trade integration. Tengia, O., Wandschneider, K., Warin, T., & Wunnava, P. (2011). Southern African economic integration: Evidence from an augmented gravity model. African Finance Journal, 13(1).
    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). Added-variable plots. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/model-diagnostics/partial-regression/

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

モデル診断のその他のグラフ