matplotlib图例句柄基础示例中的类型错误

4 投票
3 回答
9914 浏览
提问于 2025-04-18 18:51

我在理解图例处理方面遇到了一些困难。而且,官方的matplotlib图例指南中的基本示例

import matplotlib.pyplot as plt
line_up, = plt.plot([1,2,3], label='Line 2')
line_down, = plt.plot([3,2,1], label='Line 1')
plt.legend(handles=[line_up, line_down])

出现了错误,提示TypeError: __init__() got multiple values for keyword argument 'handles'

我哪里做错了呢?有没有什么想法?

我的matplotlib版本是1.3.1,我在使用Ubuntu 14.04。

以下是完整的错误追踪信息(包含上面的代码行)

heiland@note121:bauHS15_iomapsgenpod$ python testleg.py 
Traceback (most recent call last):
  File "testleg.py", line 4, in <module>
    plt.legend(handles=[line_up, line_down])
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 3381, in legend
    ret = gca().legend(*args, **kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 4778, in legend
    self.legend_ = mlegend.Legend(self, handles, labels, **kwargs)
TypeError: __init__() got multiple values for keyword argument 'handles'

3 个回答

2

我之前也遇到过同样的错误,不过上面提到的解决办法对我没用。我也更新了我的matplotlib版本,但还是没解决问题。

最后有效的办法是把legend()方法中的handles参数和要标记的图形都去掉,像这样:

    plot1 = plt.plot([1,2,3], 'b', label = 'first plot')
    plot2 = plt.plot([3,2,1], 'r', label = 'second plot')
    plt.legend()
    plt.show()

这样就能很好地显示成这个样子:

这里是图片描述

4

我遇到了和Jan一样的问题,使用的是Ubuntu 14.04上的Matplotlib 1.3.1。我试了Kobi K给出的解决办法,他的代码没有报错。但是,图例显示得不对劲: Matplotlib 1.3.1的糟糕图例 后来我把Matplotlib升级到了1.5.1,现在可以用Jan提供的代码正确显示图例了,这段代码里用了'handles'这个关键词(也就是在Matplotlib图例指南里出现的代码): Matplotlib 1.5.1的糟糕图例

9

只需要去掉 handles 这个关键词就可以了。

可以这样使用:

import matplotlib.pyplot as plt
line_up, = plt.plot([1,2,3], label='Line 2')
line_down, = plt.plot([3,2,1], label='Line 1')
plt.legend([line_up, line_down])

撰写回答