停止 matplotlib 在图例中重复标签 [英] Stop matplotlib repeating labels in legend

查看:49
本文介绍了停止 matplotlib 在图例中重复标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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"显示为蓝线 4 次.有没有比以下更优雅的方法来解决这个问题?

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 以参数为参数

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

这些参数都是可选的,默认为 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.

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())

文档 plt.legend

这篇关于停止 matplotlib 在图例中重复标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆