python type_error ai_generated true

TypeError: 'Line2D' object is not iterable

ID: python/matplotlib-legend-handle-error

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2024-05-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.7 active
3.8 active

Root Cause

Passing a single line object (not a list) to plt.legend() when it expects a list of handles, or using *args incorrectly.

generic

中文

向plt.legend()传递了单个线条对象(而非列表),但该函数期望句柄列表,或错误地使用了*args。

Workarounds

  1. 95% success Pass handles as a list
    line, = plt.plot([1,2,3]); plt.legend([line], ['my line'])
  2. 90% success Set labels during plot and call legend without arguments
    plt.plot([1,2,3], label='my line'); plt.legend()

Dead Ends

Common approaches that don't work:

  1. Wrapping the single object in a list but still getting error 60% fail

    If the list contains other non-handle objects, the error may persist.

  2. Using plt.legend() without arguments 40% fail

    This works but may not show the desired legend if labels are not set.