问题描述
这是一个非常简化的示例:
Here is a very simplified example:
xvalues = [2,3,4,6]
for x in xvalues:
plt.axvline(x,color='b',label='xvalues')
plt.legend()
图例现在将在图例中四次显示'xvalues'为蓝线.是否有比以下方法更优雅的解决方法?
The legend will now show 'xvalues' as a blue line 4 times in the legend.Is there a more elegant way of fixing this than the following?
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
对象的轴手柄的列表 - 为字符串的标签列表
- A list of axis handles which are
Artist
objects - A list of labels which are strings
这些参数都是可选的,默认为plt.gca().get_legend_handles_labels()
.您可以通过在调用legend
之前将重复的标签放入字典中来删除重复的标签.这是因为字典不能有重复的键.
These parameters are both optional defaulting to plt.gca().get_legend_handles_labels()
.You can remove duplicate labels by putting them in a dictionary before calling legend
. This is because dicts can't have duplicate keys.
例如:
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
形成收集模块.
For Python versions > 3.7
As of Python 3.7, dictionaries retain input order by default. Thus, there is no need for OrderedDict
form the collections module.
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())
这篇关于停止matplotlib在图例中重复标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!