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

Python绘制回归线至散点图时place_y函数报错求助

修复Python回归线绘制的类型错误

错误原因

  • 你错误地将整个age_x列表传入place_y函数的x参数,而place_y设计为接收单个数值。
  • slope是numpy.float64类型,Python不允许浮点数与列表直接相乘,因此触发TypeError。

修复方案

方案1:修正map函数的调用方式

保留place_y函数,通过lambda函数在map中传递单个x值:

def place_y(x, slope, intercept):
    return slope * x + intercept


def draw_line_of_regression():
    """The line of regression can be used to predict further values"""
    import matplotlib.pyplot as plt
    from scipy import stats

    age_x = [5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6]
    speed_y = [99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86]

    slope, intercept, r, p, std_error = stats.linregress(age_x, speed_y)

    # 使用lambda传递单个x值到place_y
    line_of_regression = list(map(lambda x_val: place_y(x_val, slope, intercept), age_x))

    plt.scatter(age_x, speed_y)
    plt.plot(age_x, line_of_regression)
    plt.show()


draw_line_of_regression()

方案2:使用numpy简化计算(更高效)

直接将列表转为numpy数组,无需place_y函数即可批量计算回归线的y值:

def draw_line_of_regression():
    """The line of regression can be used to predict further values"""
    import matplotlib.pyplot as plt
    from scipy import stats
    import numpy as np

    age_x = [5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6]
    speed_y = [99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86]

    slope, intercept, r, p, std_error = stats.linregress(age_x, speed_y)

    # 转换为numpy数组批量计算
    age_x_np = np.array(age_x)
    line_of_regression = slope * age_x_np + intercept

    plt.scatter(age_x, speed_y)
    plt.plot(age_x, line_of_regression)
    plt.show()


draw_line_of_regression()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 16:40:26