python runtime_error ai_generated true

UserWarning: 未找到带标签的图元可放入图例。注意,当无参数调用 legend() 时,标签以下划线开头的图元会被忽略。

UserWarning: No artists with labels found to put in legend. Note that artists whose label start with an underscore are ignored when legend() is called with no argument.

ID: python/matplotlib-legend-no-handles

其他格式: JSON · Markdown 中文 · English
80%修复率
87%置信度
0证据数
2024-08-25首次发现

版本兼容性

版本状态引入弃用备注
3.x active — — —

根因分析

调用 ax.legend() 时没有任何已绘制的图元设置了 label,或所有标签以下划线开头。

English

Calling ax.legend() without any plotted artists having a label set, or all labels starting with '_'.

generic

解决方案

  1. 97% 成功率
    ax.plot(x, y1, label='series A')
    ax.plot(x, y2, label='series B')
    ax.legend()
  2. 94% 成功率
    lines = [ax.plot(x, y1)[0], ax.plot(x, y2)[0]]
    ax.legend(lines, ['A', 'B'])

无效尝试

常见但无效的做法:

  1. 95% 失败

    There are still no labeled artists to display.

  2. 90% 失败

    A title is not a legend and does not label the plotted series.