Stop matplotlib repeating labels in legend

前端 未结 6 1520
逝去的感伤
逝去的感伤 2020-11-28 23:03

Here is a very simplified example:

xvalues = [2,3,4,6]

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

plt.legend()

Th

6条回答
  •  隐瞒了意图╮
    2020-11-28 23:53

    plt.legend takes as parameters

    1. A list of axis handles which are Artist objects
    2. A list of labels which are strings

    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.

    For example:

    For Python versions < 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())
    

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

    Docs for plt.legend

提交回复
热议问题