python
type_error
ai_generated
true
TypeError: 'Line2D'对象不可迭代
TypeError: 'Line2D' object is not iterable
ID: python/matplotlib-legend-handle-error
80%修复率
84%置信度
0证据数
2024-05-20首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.7 | active | — | — | — |
| 3.8 | active | — | — | — |
根因分析
向plt.legend()传递了单个线条对象(而非列表),但该函数期望句柄列表,或错误地使用了*args。
English
Passing a single line object (not a list) to plt.legend() when it expects a list of handles, or using *args incorrectly.
解决方案
-
95% 成功率 Pass handles as a list
line, = plt.plot([1,2,3]); plt.legend([line], ['my line'])
-
90% 成功率 Set labels during plot and call legend without arguments
plt.plot([1,2,3], label='my line'); plt.legend()
无效尝试
常见但无效的做法:
-
Wrapping the single object in a list but still getting error
60% 失败
If the list contains other non-handle objects, the error may persist.
-
Using plt.legend() without arguments
40% 失败
This works but may not show the desired legend if labels are not set.