为什么我会获得额外的标签文本而不是我放入的实际标签?

时间:2016-01-27 12:53:46

标签: python matplotlib

假设

import matplotlib.pyplot as plt

如果我从documentation

执行此操作
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], ['Line Up', 'Line Down'])

如果我将Line 2D(Line 1)传递给plt.legend()而不仅仅是标签本身,我会回复Line 1,例如relevant_line, = plt.plot(x, relevant_normal_combination, label="Relevant phrases distr.") # ... plt.legend([relevant_line, nonrelevant_line,relevant_mu, nonrelevant_mu], loc = 1) 。为什么会这样?

这是一个大约一岁的剧本,我不记得这是一年前出现的??

从我的剧本:

GridSpan

给我:

enter image description here

1 个答案:

答案 0 :(得分:2)

doc和您的代码示例之间的区别在于传递给legend的列表数量(文档中有两个,代码中有一个)

我们以下面的例子为例:

line_no_legend = plt.plot([1,2],[1,1],c="k")
line_up, = plt.plot([1,2,3], label='Line 2',color="b")
line_down, = plt.plot([3,2,1], label='Line 1',color="g")

plt.legend([line_up, line_down], ['Line Up', 'Line Down'])  #left
plt.legend([line_up, line_down])                            #middle
plt.legend(handles=[line_up, line_down])                    #right

legends behaviour

左边是文档,有两个列表:句柄和新标签(字符串)

中间的一个只有一个列表,并且颜色和标签错误。那是因为它需要一个字符串列表,而不是一个句柄列表(见legend doc

正确的方法是通过指定handles=来解决问题。