这是一个非常简单的示例:
xvalues = [2,3,4,6]
for x in xvalues:
plt.axvline(x,color='b',label='xvalues')
plt.legend()
图例现在将在图例中将“xvalues”显示为蓝线 4 次。 有没有比下面更优雅的方法来解决这个问题?
for i,x in enumerate(xvalues):
if not i:
plt.axvline(x,color='b',label='xvalues')
else:
plt.axvline(x,color='b')
最佳答案
plt.legend
作为参数
- 作为
Artist
对象的轴句柄列表 - 字符串标签列表
这些参数都是可选的,默认为 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())
Docs对于plt.legend
关于python - 停止 matplotlib 在图例中重复标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13588920/