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

基于GDP与Count列的线性回归绘图异常,求问题排查

问题分析与修正方案

嘿,我帮你检查了代码,发现几个关键问题导致图表不符合预期,咱们一个个拆解:

1. 线性回归拟合公式搞反了

你调用stats.linregress(GDP, CT)时,已经明确了GDP是自变量(x),CT是因变量(y),线性回归的拟合公式应该是 y = 斜率*x + 截距,也就是:

talent_fit = t_slope * GDP + t_int

但你现在写的是t_slope * CT + t_int,这相当于把因变量当成自变量来计算预测值,完全颠倒了x和y的关系,这是核心错误。

2. 数据点绘制方式错误

你用ax1.plot(GDP, CT, linewidth=1, marker="o")来展示原始数据,plot函数默认会把所有点按现有顺序用线条连接起来——如果你的GDP数据不是按从小到大排序的,就会画出一堆交叉混乱的线条,而不是清晰的散点分布。

正确的做法是用scatter函数绘制散点:

ax1.scatter(GDP, CT, marker="o", s=20)  # s参数控制点的大小,可选

3. 拟合线绘制未排序(导致线条混乱)

即使修正了拟合公式,如果GDP数据未排序,直接用ax1.plot(GDP, talent_fit, "b--")绘制拟合线,线条会因为x轴数据无序而跳来跳去,看起来非常奇怪。

建议先对GDP和对应的拟合值排序后再绘制:

# 获取GDP排序后的索引
sorted_indices = GDP.argsort()
# 对GDP和拟合值排序
sorted_GDP = GDP[sorted_indices]
sorted_talent_fit = talent_fit[sorted_indices]
# 绘制平滑的拟合线
ax1.plot(sorted_GDP, sorted_talent_fit, "b--", linewidth=1)

4. X轴范围设置错误

你写的ax1.set_xlim(min(CT), max(CT))把X轴范围设置成了CT的取值区间,但X轴对应的是GDP数据,这会导致图表的X轴和数据不匹配,显示异常。应该改成:

ax1.set_xlim(min(GDP), max(GDP))

修正后的完整代码示例

import matplotlib.pyplot as plt
from scipy import stats

# 假设slav_df是你的数据集
CT = slav_df.iloc[:, 4]
GDP = slav_df.iloc[:,3]

# 执行线性回归(x=GDP,y=CT)
t_slope, t_int, t_r, t_p, t_std_err = stats.linregress(GDP, CT)
# 计算拟合值(正确公式)
talent_fit = t_slope * GDP + t_int

# 绘图部分
fig, ax1 = plt.subplots(1, sharex=True)
fig.suptitle("GDP vs CT Linear Regression", fontsize=16, fontweight="bold")  # 可以加上标题

# 绘制散点图
ax1.scatter(GDP, CT, marker="o", label="Original Data")

# 排序后绘制拟合线
sorted_indices = GDP.argsort()
sorted_GDP = GDP[sorted_indices]
sorted_talent_fit = talent_fit[sorted_indices]
ax1.plot(sorted_GDP, sorted_talent_fit, "b--", linewidth=1, label=f"Fit: y={t_slope:.2f}x + {t_int:.2f}")

# 设置轴范围和标签
ax1.set_xlim(min(GDP), max(GDP))
ax1.set_xlabel("GDP")
ax1.set_ylabel("CT")  # 建议填上实际的列名,方便理解
ax1.legend()  # 显示图例

plt.show()

这样修改后,图表应该就能符合预期了——散点清晰展示原始数据分布,拟合线平滑呈现线性关系~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:47:05