matplotlib调用ax.legend()仍报No handles with labels found错误求解
问题根因
你的代码无法生成图例是两个核心问题共同导致的:
- 调用
plt.scatter()时仅声明了色卡参数cmap,没有传入c参数指定映射颜色的关联字段,matplotlib没有分类着色的依据,也无法自动关联分类标签 - 绘图时没有设置
label参数,也没有手动给ax.legend()传入自定义的图例句柄和标签列表,ax.legend()无法检索到有效生成图例的信息,自然返回找不到带标签的句柄的错误。
修复方案
你可以根据需求选择以下两种修复方式:
方式1:分组绘图自动生成图例(推荐)
遍历labels字段的不同取值分组绘图,每组单独指定label参数,matplotlib可自动生成对应图例:
import pandas as pd import matplotlib.pyplot as plt test_data = pd.DataFrame.from_dict({'x': {0: 9.480850219726562, 1: 14.477883338928223, 2: 5.063024044036865, 3: 11.274681091308594, 4: 5.3310112953186035}, 'y': {0: 1.3540315628051758, 1: 9.007585525512695, 2: 7.3623576164245605, 3: 7.365053653717041, 4: 6.734741687774658}, 'labels': {0: 71, 1: 26, 2: 42, 3: -1, 4: -1}}) fig, ax = plt.subplots(figsize=(20, 10)) # 按标签分组绘图 for label, group in test_data.groupby('labels'): ax.scatter(group.x, group.y, label=label, cmap='hsv_r') ax.legend() plt.show()
方式2:单批次绘图后手动构造图例
如果不需要分组绘图,你可以传入c参数指定着色字段后,手动构造图例句柄传入ax.legend():
import pandas as pd import matplotlib.pyplot as plt from matplotlib.colors import Normalize import matplotlib.patches as mpatches test_data = pd.DataFrame.from_dict({'x': {0: 9.480850219726562, 1: 14.477883338928223, 2: 5.063024044036865, 3: 11.274681091308594, 4: 5.3310112953186035}, 'y': {0: 1.3540315628051758, 1: 9.007585525512695, 2: 7.3623576164245605, 3: 7.365053653717041, 4: 6.734741687774658}, 'labels': {0: 71, 1: 26, 2: 42, 3: -1, 4: -1}}) fig, ax = plt.subplots(figsize=(20, 10)) cmap = plt.get_cmap('hsv_r') norm = Normalize(vmin=test_data.labels.min(), vmax=test_data.labels.max()) # 指定按labels字段着色 scatter = ax.scatter(test_data.x, test_data.y, c=test_data.labels, cmap=cmap, norm=norm) # 手动构造图例项 unique_labels = test_data.labels.unique() handles = [mpatches.Patch(color=cmap(norm(l)), label=str(l)) for l in unique_labels] ax.legend(handles=handles) plt.show()
内容的提问来源于stack exchange,提问作者Fiori
相关产品推荐
相关产品推荐

