Stop matplotlib repeating labels in legend

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

    Based on answer https://stackoverflow.com/a/13589144/9132798 and https://stackoverflow.com/a/19386045/9132798 plt.gca().get_legend_handles_labels()[1] gives a list of names, it is possible to check if the label is already in the list while in the loop plotting (label= name[i] if name[i] not in plt.gca().get_legend_handles_labels()[1] else ''). For the given example this solution would look like:

    import matplotlib.pyplot as plt
    
    xvalues = [2,3,4,6]
    
    for x in xvalues:
        plt.axvline(x,color='b',\
        label= 'xvalues' if 'xvalues' \
                not in plt.gca().get_legend_handles_labels()[1] else '')
    
    plt.legend()
    

    Which is much shorter than https://stackoverflow.com/a/13589144/9132798 and more flexible than https://stackoverflow.com/a/19386045/9132798 as it could be use for any kind of loop any plot function in the loop individually. However, for many cycles it probably slower than https://stackoverflow.com/a/13589144/9132798.

提交回复
热议问题