python - 停止 matplotlib 在图例中重复标签

标签 python matplotlib legend

这是一个非常简单的示例:

xvalues = [2,3,4,6]

for x in xvalues:
    plt.axvline(x,color='b',label='xvalues')

plt.legend()

enter image description here

图例现在将在图例中将“xvalues”显示为蓝线 4 次。 有没有比下面更优雅的方法来解决这个问题?

for i,x in enumerate(xvalues):
    if not i:
        plt.axvline(x,color='b',label='xvalues')
    else:
        plt.axvline(x,color='b')

enter image description here

最佳答案

plt.legend 作为参数

  1. 作为 Artist 对象的轴句柄列表
  2. 字符串标签列表

这些参数都是可选的,默认为 plt.gca().get_legend_handles_labels()。 您可以通过在调用 legend 之前将重复标签放入字典中来删除重复标签。这是因为字典不能有重复的键。

例如:

对于 Python 版本 <3.7

from collections import OrderedDict
import matplotlib.pyplot as plt

handles, labels = plt.gca().get_legend_handles_labels()
by_label = OrderedDict(zip(labels, handles))
plt.legend(by_label.values(), by_label.keys())

对于 Python 版本 > 3.7

从 Python 3.7 开始,字典默认保留输入顺序。因此,集合模块中不需要 OrderedDict

import matplotlib.pyplot as plt

handles, labels = plt.gca().get_legend_handles_labels()
by_label = dict(zip(labels, handles))
plt.legend(by_label.values(), by_label.keys())

enter image description here

Docs对于plt.legend

关于python - 停止 matplotlib 在图例中重复标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13588920/

相关文章:

python - 从字典列表中删除键值对

python - 将图例或背景图像添加到 Igraph 0.6 (for python) 图中

matlab - 隐藏图例中的线

python - 如何获取PyQt QGraphicsTextItem不透明区域

python - 将数据框中的嵌套列表列更改为字典?

python - subprocess.Popen 需要什么权限?

python - 为什么我的箱线图没有出现在 python 中?

python - 将 pandas DataFrame 图插入 matplotlib 子图中

python - 将 y 轴格式化为百分比

python - 如何设置图例标记大小和 alpha?