Stop matplotlib repeating labels in legend

前端 未结 6 1564
逝去的感伤
逝去的感伤 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:43

    I don't know if this can be considered "elegant", but you can have your label a variable that gets set to "_nolegend_" after first usage:

    my_label = "xvalues"
    xvalues = [2,3,4,6]
    
    for x in xvalues:
        plt.axvline(x, color='b', label=my_label)
        my_label = "_nolegend_"
    
    plt.legend()
    

    This can be generalized using a dictionary of labels if you have to put several labels:

    my_labels = {"x1" : "x1values", "x2" : "x2values"}
    x1values = [1, 3, 5]
    x2values = [2, 4, 6]
    
    for x in x1values:
        plt.axvline(x, color='b', label=my_labels["x1"])
        my_labels["x1"] = "_nolegend_"
    for x in x2values:
        plt.axvline(x, color='r', label=my_labels["x2"])
        my_labels["x2"] = "_nolegend_"
    
    plt.legend()
    

    (Answer inspired by https://stackoverflow.com/a/19386045/1878788)

提交回复
热议问题