Matplotlib 编辑图例标签

l73*_*36x 5 python matplotlib

如果我修改绘图的标签plt.legend([some labels]),然后我打电话,ax.get_legend_handles_labels()我会取回旧标签。

这是一个简单的例子:

In [1]: import matplotlib.pyplot as plt

In [2]: plt.plot([1,2,3], label='A')
Out[2]: [<matplotlib.lines.Line2D at 0x7f60749be310>]

In [3]: plt.plot([2,3,4], label='B')
Out[3]: [<matplotlib.lines.Line2D at 0x7f60749f1850>]

In [4]: ax = plt.gca()

In [5]: l = ax.get_legend_handles_labels()

In [6]: l
Out[6]:
([<matplotlib.lines.Line2D at 0x7f60749be310>,
  <matplotlib.lines.Line2D at 0x7f60749f1850>],
 [u'A', u'B'])

In [7]: plt.legend(['C', 'D'])  ### This correctly modifies the legend to show 'C' and 'D', but then ...
Out[7]: <matplotlib.legend.Legend at 0x7f6081dce190>

In [10]: l = ax.get_legend_handles_labels()

In [11]: l
Out[11]:
([<matplotlib.lines.Line2D at 0x7f60749be310>,
  <matplotlib.lines.Line2D at 0x7f60749f1850>],
 [u'A', u'B'])
Run Code Online (Sandbox Code Playgroud)

此时我不知道如何检索显示的标签列表,即['C', 'D']。我缺少什么?我还应该使用什么其他方法?

为了提供更多背景信息,我想做的是绘制 pandas 数据框,修改图例以添加一些信息,然后在同一轴上绘制另一个数据框,并使用标签重复相同的过程。为此,第二次我需要修改图例中的部分标签并保持其余部分不变。

M4r*_*ini 5

执行功能文档中建议的操作即可plt.legend完成您想要的操作。

签名: plt.legend(*args, **kwargs) 文档字符串:在轴上放置图例。

要为轴上已经存在的线创建图例(例如通过绘图),只需使用可迭代的字符串(每个图例项目一个)调用此函数即可。例如::

ax.plot([1, 2, 3])
ax.legend(['A simple line'])
Run Code Online (Sandbox Code Playgroud)

然而,为了将“标签”和图例元素实例保持在一起,最好在艺术家创建时指定标签,或者通过调用~matplotlib.artist.Artist.set_label艺术家的 :meth: 方法::

line, = ax.plot([1, 2, 3], label='Inline label')
# Overwrite the label by calling the method.
line.set_label('Label via method')
ax.legend()
Run Code Online (Sandbox Code Playgroud)
import matplotlib.pyplot as plt

line1, = plt.plot([1,2,3], label='A')
line2, = plt.plot([2,3,4], label='B')

ax = plt.gca()
l = ax.get_legend_handles_labels()
print(l)

line1.set_label("C")
line2.set_label("D")
ax.legend()

l = ax.get_legend_handles_labels()
print(l)
plt.show()

>>([<matplotlib.lines.Line2D object at 0x000000000A399EB8>, <matplotlib.lines.Line2D object at 0x0000000008A67710>], ['A', 'B'])
>>([<matplotlib.lines.Line2D object at 0x000000000A399EB8>, <matplotlib.lines.Line2D object at 0x0000000008A67710>], ['C', 'D'])
Run Code Online (Sandbox Code Playgroud)