python - Matplotlib 编辑图例标签

标签 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'])

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

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

最佳答案

按照 plt.legend 的函数文档中的建议进行操作完成你想要的。

Signature: plt.legend(*args, **kwargs) Docstring: Places a legend on the axes.

To make a legend for lines which already exist on the axes (via plot for instance), simply call this function with an iterable of strings, one for each legend item. For example::

ax.plot([1, 2, 3])
ax.legend(['A simple line'])

However, in order to keep the "label" and the legend element instance together, it is preferable to specify the label either at artist creation, or by calling the :meth:~matplotlib.artist.Artist.set_label method on the artist::

line, = ax.plot([1, 2, 3], label='Inline label')
# Overwrite the label by calling the method.
line.set_label('Label via method')
ax.legend()
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'])

关于python - Matplotlib 编辑图例标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35033782/

相关文章:

python - 如何在 sqlite 查询中插入 Python 变量?

python - 在 QTableWidget 中获取选定行数 - PyQt

python - zip 中的键和值

python - 两个字符串之间的正则表达式匹配python

python - "Only size-1 arrays can be converted to Python scalars"

python - 使用 python 3 对 url 进行编码

python matplotlib : how to automatically save figures in . 图格式?

python - 在Python中重新排列图像

python - Matplotlib/SNS : plot histogram but with average of another variable on the y-axis

python - 如何将中点圆算法 "translate"导入matplotlib?