You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python的qqplot中获取拟合回归线的截距与斜率?

获取QQ图中拟合回归线的截距与斜率

当使用statsmodels.api.sm.qqplot()并设置line="r"时,红色回归线是通过样本分位数与理论分位数的线性回归得到的。你可以通过以下步骤手动计算该线条的截距和斜率:

步骤说明

  1. 提取样本数据的分位数
  2. 生成对应理论分布的分位数
  3. 对两组分位数做线性回归,得到模型参数

完整代码示例

import statsmodels.api as sm
import scipy.stats as stats
import numpy as np
from sklearn.linear_model import LinearRegression

# 生成示例数据
np.random.seed(100)
a = np.random.normal(0, 4, 100)
dist = stats.norm(loc=5, scale=1)

# 1. 计算样本分位数和理论分位数
# 取5%到95%的分位数区间,和qqplot默认逻辑一致
p = np.linspace(0.05, 0.95, 91)
sample_quantiles = np.percentile(a, p * 100)
theoretical_quantiles = dist.ppf(p)

# 2. 拟合线性回归
X = theoretical_quantiles.reshape(-1, 1)
y = sample_quantiles.reshape(-1, 1)

model = LinearRegression()
model.fit(X, y)

# 提取参数
slope = model.coef_[0][0]
intercept = model.intercept_[0]

print(f"回归线斜率: {slope:.4f}")
print(f"回归线截距: {intercept:.4f}")

# 验证:绘制qqplot并对比手动计算的回归线
fig = sm.qqplot(a, dist, line="r")
ax = fig.gca()
ax.plot(theoretical_quantiles, intercept + slope * theoretical_quantiles, color="blue", linestyle="--", label="手动计算回归线")
ax.legend()

补充说明

  • statsmodels的qqplot中line="r"的计算逻辑和上述代码完全一致,都是基于分位数的线性回归
  • 若偏好使用statsmodels自带的线性回归模块,可替换为以下代码:
X_sm = sm.add_constant(theoretical_quantiles)
model_sm = sm.OLS(sample_quantiles, X_sm).fit()
print(f"截距: {model_sm.params[0]:.4f}, 斜率: {model_sm.params[1]:.4f}")

内容的提问来源于stack exchange,提问作者statwoman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 20:05:25