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

创建legend时出现TypeError: 'list'对象不可调用的问题排查

问题解决与说明

错误原因与代码修正

你的报错核心是把matplotlib的函数当成变量直接赋值了。plt.xlabel、plt.ylabel、plt.legend都是需要调用的函数,不是可直接赋值的变量。你写的plt.xlabel="age"会把字符串覆盖原函数对象,导致后续调用时出现“对象不可调用”的错误。

修正后的代码如下:

plt.figure(figsize=(10,6))
plt.scatter(df.age[df.target==1],
           df.thalach[df.target==1],
           color="salmon")

plt.scatter(df.age[df.target==0],
           df.thalach[df.target==0],
           color="lightblue")

# 改为函数调用形式,传递参数
plt.xlabel("age")
plt.ylabel("max heart rate")
plt.legend(["disease","No disease"])
plt.show()

如果之前的Notebook会话里已经因为误赋值搞乱了plt的函数,直接重启Jupyter内核再运行修正代码即可。

同一Jupyter Notebook绘制多个图的方法

完全可以绘制多个图,推荐两种实用方法:

  • 全局plt方式:每次绘图前调用plt.figure()创建新画布,确保每个图独立:
    # 第一个图
    plt.figure(figsize=(10,6))
    plt.scatter(df.age[df.target==1], df.thalach[df.target==1], color="salmon")
    plt.xlabel("age")
    plt.legend(["disease"])
    
    # 第二个图
    plt.figure(figsize=(8,4))
    plt.hist(df.thalach, bins=15, color="lightblue")
    plt.xlabel("max heart rate")
    
  • 面向对象方式(更稳定,推荐):用plt.subplots()创建独立的画布和轴对象,避免全局plt的冲突:
    # 第一个图
    fig1, ax1 = plt.subplots(figsize=(10,6))
    ax1.scatter(df.age[df.target==1], df.thalach[df.target==1], color="salmon")
    ax1.set_xlabel("age")
    ax1.legend(["disease"])
    
    # 第二个图
    fig2, ax2 = plt.subplots(figsize=(8,4))
    ax2.hist(df.thalach, bins=15, color="lightblue")
    ax2.set_xlabel("max heart rate")
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 05:36:09