python runtime_error ai_generated true

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-08-25First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

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

generic

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 95% fail

    There are still no labeled artists to display.

  2. 90% fail

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