python
type_error
ai_generated
true
TypeError: 'Line2D' object is not iterable
ID: python/matplotlib-legend-handle-error
80%Fix Rate
84%Confidence
0Evidence
2024-05-20First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 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
-
95% success Pass handles as a list
line, = plt.plot([1,2,3]); plt.legend([line], ['my line'])
-
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:
-
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.
-
Using plt.legend() without arguments
40% fail
This works but may not show the desired legend if labels are not set.