gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 05:51:45 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com