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

Python中如何为残差图绘制分X区间的两条均值线?

绘制带分段均值线的残差图

我明白你想让残差图更直观,帮不懂统计的人一眼看出中途数值骤降的规律——给指定X区间分别添加残差均值线是个很棒的做法。下面是调整后的完整代码,我会标注关键改动:

# --------------- 原有线性模型代码 ---------------
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from scipy.stats import norm

# 假设merged是你的预处理DataFrame,确保已提前加载
x = merged[['Imp_Col_LNG', 'AveSH_LNG']].values
y = merged['Unproductive_LNG'].values

reg = LinearRegression()
reg.fit(x,y)
yp = reg.predict(x)

# --------------- 残差计算与分段均值线绘制 ---------------
# 计算残差
res = pd.Series(y - yp)

# 1. 划分两个指定区间(这里的X指预测值yp,若需替换为原始特征,直接换成merged['对应特征名']即可)
mask1 = (yp >= 0) & (yp <= 110)
mask2 = (yp > 110) & (yp <= 240)

# 2. 计算每个区间的残差均值
mean_res1 = res[mask1].mean()
mean_res2 = res[mask2].mean()

# --------------- 绘制残差趋势图(带分段均值线)---------------
plt.figure(figsize=(10,6))
plt.plot(res, label='Residuals')

# 用不同颜色虚线绘制均值线,添加清晰标签方便理解
plt.axhline(y=mean_res1, color='red', linestyle='--', label=f'Mean Residual (0 ≤ Predicted ≤ 110): {mean_res1:.2f}')
plt.axhline(y=mean_res2, color='blue', linestyle='--', label=f'Mean Residual (110 < Predicted ≤ 240): {mean_res2:.2f}')

plt.xlabel('Data Point Index')
plt.ylabel('Residual Value')
plt.title('Residual Plot with Segment Mean Lines')
plt.legend()
plt.grid(alpha=0.3)
plt.show()

# --------------- 可选:绘制残差vs预测值散点图(更推荐的统计可视化方式)---------------
plt.figure(figsize=(10,6))
plt.scatter(yp, res, alpha=0.6, label='Residuals')
plt.axhline(y=mean_res1, color='red', linestyle='--', label=f'Mean Residual (0 ≤ Predicted ≤ 110): {mean_res1:.2f}')
plt.axhline(y=mean_res2, color='blue', linestyle='--', label=f'Mean Residual (110 < Predicted ≤ 240): {mean_res2:.2f}')
# 添加区间分隔线,强化分界点
plt.axvline(x=110, color='gray', linestyle=':', label='Segment Boundary (Predicted = 110)')

plt.xlabel('Predicted Values')
plt.ylabel('Residual Value')
plt.title('Residuals vs Predicted Values with Segment Means')
plt.legend()
plt.grid(alpha=0.3)
plt.show()

# --------------- 原有残差检查代码(按需保留)---------------
# checkresiduals(res)  # 若使用statsmodels工具,需提前导入对应模块

关键改动说明:

  • 区间灵活划分:用mask1和mask2筛选目标区间的残差数据,如果你的"X区间"指的是原始输入特征(比如Imp_Col_LNG),只需把代码里的yp替换成merged['对应特征列名']即可。
  • 均值针对性计算:单独计算两个区间的残差均值,能直接展示两段数据的残差整体水平差异,非统计背景的人也能快速理解。
  • 可视化优化:用不同颜色区分均值线,添加明确标签和网格,再配合可选的区间分隔线,让骤降的规律一目了然。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 17:52:55