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

运行Matplotlib代码报错No handles with labels found to put in legend是什么问题?

报错原因及解决方案

错误核心原因

该报错的本质是 plt.legend() 生效的画布上,没有任何携带 label 参数的绘图对象(比如折线、散点等可被图例识别的handle)。对应你提供的代码,具体问题出在执行顺序错误:

  • 你先在matplotlib自动创建的默认画布上调用了5次plt.plot(),给每条折线都设置了合法的label参数
  • 接着调用plt.figure(figsize=(10,6))创建了全新的空白画布,后续所有的plt.xlabel、plt.ylabel、plt.legend()都会默认作用在这个新画布上
  • 新画布上没有任何绘制的图形,更没有带label的对象,因此调用图例生成接口时直接抛出对应错误

修复方案

将plt.figure(figsize=(10,6))的调用位置移动到所有plt.plot()代码之前即可,修改后的正确代码如下:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

data3=pd.read_csv(r'10.7 and res.csv')
data=np.array(data3)
x=np.linspace(0,20,1023)

# 先创建指定尺寸的画布,再在该画布上执行绘图操作
plt.figure(figsize=(10,6))
plt.plot(x,data[:,0],label='Ihh')
plt.plot(x,data[:,1],label='Ihv')
plt.plot(x,data[:,2],label='Ivh')
plt.plot(x,data[:,3],label='Ivv')
plt.plot(x,data[:,4],label='Response funtion')
plt.xlabel('Time in ns')
plt.ylabel('No of count')
plt.legend(loc='upper right')
plt.show()

其他可能触发该报错的场景

  • 调用plt.plot()时写错了参数名,比如把label误写为lable,导致绘图对象没有携带标签属性
  • 手动指定图例时传入的handles列表为空,或者对应handles没有绑定label属性
  • 多子图场景下,在没有绘图的子图上调用了图例生成接口

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 21:06:03