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

使用Python绘制散点图与回归线遇到问题求助

问题排查与修复建议

1. 提前计算平均值触发除以零错误

函数开头初始化的sum_of_x和sum_of_y是空列表,此时直接计算平均值,len(sum_of_x)为0,必然触发ZeroDivisionError。平均值计算必须在读取完所有数据之后执行。

2. 列表append方法使用错误

list.append()方法无返回值(返回None),不能将其结果赋值给原列表:

sum_of_x = sum_of_x.append(values[1])  # 错误,执行后sum_of_x会变成None
sum_of_y = sum_of_y.append(values[1])  # 错误,同上

正确写法是直接调用append,无需赋值:

sum_of_x.append(int(values[0]))  # 取values[0]作为x值,同时转成数值类型
sum_of_y.append(int(values[1]))

3. x、y数据索引错误

代码中sum_of_x和sum_of_y都添加了values[1],导致x、y列表完全一致,不符合需求。需分别取values[0](x坐标)和values[1](y坐标),且要转换为数值类型才能参与后续计算。

修复后的完整代码示例

import turtle
t = turtle.Turtle()
wn = turtle.Screen()
turtle.setworldcoordinates(-100, -100, 100, 100)
wn.bgcolor('lightblue')
t.pencolor('red')

def plotregression():
    sum_of_x = []
    sum_of_y = []
    # 先读取所有数据,填充列表并绘制散点
    with open('data.txt', 'r') as filename:  # 使用with语句自动管理文件,更安全
        for line in filename:
            values = line.strip().split()  # 去除换行和多余空格,避免空值干扰
            if len(values) != 2:  # 跳过格式错误的行
                continue
            x = int(values[0])
            y = int(values[1])
            sum_of_x.append(x)
            sum_of_y.append(y)
            # 绘制散点
            t.up()
            t.goto(x, y)
            t.down()
            t.stamp()
    
    # 数据读取完成后计算平均值和斜率
    if not sum_of_x:  # 处理空数据的极端情况
        print("数据文件为空或格式错误")
        return
    mean_of_x = sum(sum_of_x) / len(sum_of_x)
    mean_of_y = sum(sum_of_y) / len(sum_of_y)
    
    # 计算简单线性回归的斜率
    numerator = sum((x - mean_of_x) * (y - mean_of_y) for x, y in zip(sum_of_x, sum_of_y))
    denominator = sum((x - mean_of_x) ** 2 for x in sum_of_x)
    if denominator == 0:
        print("所有x值相同,无法计算回归线斜率")
        return
    slope = numerator / denominator
    
    # 可选:绘制回归线
    t.pencolor('blue')
    x_min = min(sum_of_x)
    x_max = max(sum_of_x)
    y_min = mean_of_y + slope * (x_min - mean_of_x)
    y_max = mean_of_y + slope * (x_max - mean_of_x)
    t.up()
    t.goto(x_min, y_min)
    t.down()
    t.goto(x_max, y_max)

plotregression()
wn.exitonclick()

额外注意事项

  • 用with open(...)管理文件,避免忘记关闭文件或异常导致的资源泄漏。
  • 添加数据格式校验,跳过无效行,防止索引越界错误。
  • 处理空数据、x值全相同的极端情况,避免再次触发除以零错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 03:45:48