分位数回归过程
斜率如何随条件分布变化,并与单一的 OLS 估计相对照。

OLS 只估计一个斜率:对条件均值的效应。分位数回归则为每个条件分位数 τ 估计一个斜率,从而可以看出某个预测变量是在拉伸分布,而不仅仅是平移分布。深色线是 τ = 0.05 … 0.95 时的分位数回归系数及其 95% 置信带;橙色线和虚线分别是 OLS 估计及其 95% 置信区间,按构造为常数。左图展示数据以及若干条拟合的分位数回归线。
背景设定为 Troadec 与 Warin (2015),即 L'économie du Québec 2015 中探讨加拿大企业在全球研发中地位的一章。数据为说明用途而模拟生成,并非该章的数据或结果:n = 300 家企业,以研发投资的对数对销售额的对数(均以百万美元计)回归,因此每个斜率都是弹性。模型用 smf.quantreg().fit(q=τ) 和 smf.ols() 拟合。
代码及图中文字均为英文。
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 Troadec & Warin (2015) [troadec2015]
# Data: 300 firms; the spread of R&D widens with firm size
rng = np.random.default_rng(2015)
n = 300
log_sales = rng.uniform(3, 11, n)
df = pd.DataFrame({"log_sales": log_sales,
"log_rd": -3 + 0.85 * log_sales + (0.2 + 0.13 * log_sales) * rng.normal(size=n)})
quantiles = np.arange(0.05, 0.96, 0.05)
# Fit one quantile regression per τ and keep slope + 95% CI
rows = []
for q in quantiles:
fit = smf.quantreg("log_rd ~ log_sales", df).fit(q=q)
lo, hi = fit.conf_int().loc["log_sales"]
rows.append((q, fit.params["Intercept"], fit.params["log_sales"], lo, hi))
qr = np.array(rows)
ols = smf.ols("log_rd ~ log_sales", df).fit()
ols_lo, ols_hi = ols.conf_int().loc["log_sales"]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 5.65), layout="constrained",
gridspec_kw=dict(width_ratios=[1, 1.25]))
fig.get_layout_engine().set(rect=(0, 0, 1, 0.885)) # keep the top of the figure for the title and subtitle
# Left: data with selected quantile lines and the OLS line
ax1.scatter(df.log_sales, df.log_rd, s=14, color="#8E8E93", alpha=0.5, lw=0)
x = np.linspace(df.log_sales.min(), df.log_sales.max(), 50)
for q, a, s_, *_ in qr[[0, 4, 9, 14, 18]]:
ax1.plot(x, a + s_ * x, color="#007AFF", lw=1.2, alpha=0.4 + 0.6 * (q == 0.5))
ax1.text(x[-1] + 0.1, a + s_ * x[-1], f"τ = {q:.2f}", fontsize=8.5, color="#007AFF", va="center")
ax1.plot(x, ols.params["Intercept"] + ols.params["log_sales"] * x, color="#FF9500", lw=2, ls="--")
ax1.set_xlim(right=x[-1] + 1.6)
ax1.set_xlabel("Sales (log US$ millions)")
ax1.set_ylabel("R&D investment (log US$ millions)")
ax1.set_title("Quantile lines fan out", fontsize=12)
# Right: slope estimates across τ vs the OLS slope
ax2.fill_between(qr[:, 0], qr[:, 3], qr[:, 4], color="#007AFF", alpha=0.15, lw=0)
ax2.plot(qr[:, 0], qr[:, 2], "o-", color="#007AFF", ms=5, mec="white", mew=1, label="Quantile regression (95% CI)")
ax2.axhline(ols.params["log_sales"], color="#FF9500", lw=2, label="OLS (95% CI)")
for v in (ols_lo, ols_hi):
ax2.axhline(v, color="#FF9500", lw=1, ls="--")
ax2.set_xticks(np.arange(0.1, 1.0, 0.1))
ax2.set_xlabel("Quantile τ of log R&D investment")
ax2.set_ylabel("Slope: elasticity of R&D to sales")
ax2.legend(loc="upper left")
ax2.set_title("Sales elasticity by quantile", fontsize=12)
slope = dict(zip(np.round(qr[:, 0], 2), qr[:, 2]))
fig.text(0.01, 0.947, "Sales matter more for R&D at the top of the distribution",
fontsize=15, fontweight="semibold", va="bottom")
fig.text(0.01, 0.903, f"n = {len(df)} firms (simulated) · elasticity at τ = .10: {slope[0.1]:.2f}, "
f"τ = .50: {slope[0.5]:.2f}, τ = .90: {slope[0.9]:.2f} · OLS: {ols.params['log_sales']:.2f} "
f"[{ols_lo:.2f}, {ols_hi:.2f}]", 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. - Troadec & Warin (2015), Canadian firms in global R&D. Troadec, A., & Warin, T. (2015). La place des entreprises canadiennes dans la R-D mondiale. In B. Sinclair-Desgagné, A. Van Assche & T. Warin (Eds.), L'économie du Québec 2015 : contexte et enjeux internationaux (ch. 4, pp. 109–125). Presses internationales Polytechnique.
The example is set in the context of this chapter; unless its description says otherwise, the numbers are simulated and are not the chapter's data or results.
这些示例用于说明统计方法。除条目另有说明外,其数值均为模拟数据,图表标题描述的是该图在这些模拟数据中呈现的内容——既不是所引论文的结论,也不是作者对实质问题的立场。关于结果、背景和数据,请以此处引用的论文为准。
如何引用
PyStatlas 由 Thierry Warin 创建并维护。如果它对你的工作有所帮助,敬请引用。
Warin, T. (2026). Quantile regression process. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/regression-models/quantile-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}
}