交互效应
均值 ± 1 SD 处的简单斜率与 Johnson–Neyman 图:资本流入与信贷增长的关系,受汇率弹性调节。

交互项意味着一个预测变量的斜率取决于另一个变量。左图在调节变量的三个取值——均值及 ±1 个标准差——处分别画出该斜率,各附 95% 置信带。右图是 Johnson–Neyman 视图:焦点预测变量的边际效应 β₁ + β₃·moderator 在调节变量整个取值范围内的变化,附 95% 置信区间。置信带不包含零的区域效应显著;转折点即 Johnson–Neyman 点。
背景设定为 Stojkov 与 Warin (2021, Global Economy Journal) 从蒙代尔三元悖论视角研究外国资本与国内融资条件。数据为说明用途而模拟生成,并非论文的数据或结果:n = 400 个国家-年份,因变量为国内信贷增长率(%),焦点预测变量为净资本流入(占 GDP 的 %),调节变量为汇率弹性指数(0 = 硬钉住,1 = 自由浮动),模型为 smf.ols("credit ~ inflows * flex")。在钉住汇率下,资本流入伴随更快的信贷增长;汇率浮动越自由,这种关联越弱。边际效应的方差由 cov_params() 手工计算:Var(β₁) + 2m·Cov(β₁, β₃) + m²·Var(β₃)。
代码及图中文字均为英文。
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
from scipy import stats
# Simulated data, set in the context of Stojkov & Warin (2021) [stojkov2021credit]
# Data: 400 country-years; inflows raise credit growth less as flexibility rises
rng = np.random.default_rng(2021)
n = 400
df = pd.DataFrame({"inflows": rng.normal(4, 3, n), "flex": rng.beta(1.5, 1.5, n)})
df["credit"] = (5 + 1.2 * df.inflows + 1.5 * df.flex - 1.3 * df.inflows * df.flex
+ rng.normal(0, 5, n))
model = smf.ols("credit ~ inflows * flex", data=df).fit()
b, V = model.params, model.cov_params()
t_crit = stats.t.ppf(0.975, model.df_resid)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 5.65), layout="constrained")
fig.get_layout_engine().set(rect=(0, 0, 1, 0.885)) # keep the top of the figure for the title and subtitle
# Left: simple slopes of inflows at flexibility = mean − 1 SD, mean, mean + 1 SD
ax1.scatter(df.inflows, df.credit, s=12, color="#C7C7CC", alpha=0.6, lw=0)
x = np.linspace(df.inflows.min(), df.inflows.max(), 100)
m, s = df.flex.mean(), df.flex.std()
for f, lab, c in [(m - s, "−1 SD", "#5AC8FA"), (m, "Mean", "#007AFF"), (m + s, "+1 SD", "#AF52DE")]:
pred = model.get_prediction(pd.DataFrame({"inflows": x, "flex": f})).summary_frame()
ax1.fill_between(x, pred.mean_ci_lower, pred.mean_ci_upper, color=c, alpha=0.15, lw=0)
ax1.plot(x, pred["mean"], color=c, lw=2.2,
label=f"{lab} ({f:.2f}): slope {b['inflows'] + b['inflows:flex'] * f:+.2f}")
ax1.legend(title="Exchange-rate flexibility", loc="upper left", alignment="left")
ax1.set_ylim(top=df.credit.max() + 14)
ax1.set_xlabel("Net capital inflows (% of GDP)")
ax1.set_ylabel("Domestic credit growth (%)")
ax1.set_title("Simple slopes of inflows at three regimes", fontsize=12)
# Right: Johnson–Neyman — marginal effect of inflows across flexibility, with 95% CI
flex = np.linspace(df.flex.min(), df.flex.max(), 400)
eff = b["inflows"] + b["inflows:flex"] * flex
se = np.sqrt(V.loc["inflows", "inflows"] + 2 * flex * V.loc["inflows", "inflows:flex"]
+ flex**2 * V.loc["inflows:flex", "inflows:flex"])
lo, hi = eff - t_crit * se, eff + t_crit * se
sig = (lo > 0) | (hi < 0)
ax2.axhline(0, color="#8E8E93", lw=1, ls="--")
ax2.fill_between(flex, lo, hi, where=sig, color="#007AFF", alpha=0.18, lw=0, label="p < .05")
ax2.fill_between(flex, lo, hi, where=~sig, color="#AEAEB2", alpha=0.3, lw=0, label="n.s.")
ax2.plot(flex, eff, color="#1D1D1F", lw=2)
jns = flex[1:][np.diff(sig.astype(int)) != 0] # where significance switches
for jn in jns:
ax2.axvline(jn, color="#007AFF", lw=1, ls=":")
ax2.annotate(f"Johnson–Neyman point\nflexibility = {jn:.2f}", (jn, 0.97), xytext=(-8, 0),
xycoords=ax2.get_xaxis_transform(), textcoords="offset points",
fontsize=9.5, color="#007AFF", va="top", ha="right")
# Rug of the observed moderator values
ax2.plot(df.flex, np.full(len(df), 0.015), "|", ms=7, color="#8E8E93", alpha=0.4,
transform=ax2.get_xaxis_transform())
share = (df.flex < jns[0]).mean()
ax2.legend(loc="lower left", bbox_to_anchor=(0, 0.06))
ax2.set_xlabel("Exchange-rate flexibility (moderator, 0 = peg, 1 = float)")
ax2.set_ylabel("Credit growth points per +1 pp of inflows")
ax2.set_title(f"Significantly positive below {jns[0]:.2f} ({share:.0%} of country-years)", fontsize=12)
# Figure title and statistical subtitle above both panels
p_int = model.pvalues["inflows:flex"]
p_txt = "p < .001" if p_int < 0.001 else f"p = {p_int:.3f}"
fig.text(0.01, 0.947, "Capital inflows feed credit growth under pegs, much less under floats",
fontsize=15, fontweight="semibold", va="bottom")
fig.text(0.01, 0.903, f"OLS · n = {int(model.nobs)} country-years (simulated) · inflows × flexibility: "
f"β = {b['inflows:flex']:.2f}, t({model.df_resid:.0f}) = {model.tvalues['inflows:flex']:.2f}, "
f"{p_txt} · R² = {model.rsquared:.2f} · bands = 95% CI",
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. - Stojkov & Warin (2021), foreign capital and domestic funding conditions. Stojkov, A., & Warin, T. (2021). Foreign capital and domestic funding conditions: A Mundellian trilemma perspective. Global Economy Journal, 21, 2150008. https://doi.org/10.1142/s2194565921500081
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 effects. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/regression-models/interaction-effects/
@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}
}