How is order of items in matplotlib legend determined?

后端 未结 5 757
迷失自我
迷失自我 2020-12-12 17:43

I am having to reorder items in a legend, when I don\'t think I should have to. I try:

from pylab import *
clf()
ax=gca()
ht=ax.add_patch(Rectangle((1,1),1,1,         


        
5条回答
  •  独厮守ぢ
    2020-12-12 18:30

    Here's a quick snippet to sort the entries in a legend. It assumes that you've already added your plot elements with a label, for example, something like

    ax.plot(..., label='label1')
    ax.plot(..., label='label2')
    

    and then the main bit:

    handles, labels = ax.get_legend_handles_labels()
    # sort both labels and handles by labels
    labels, handles = zip(*sorted(zip(labels, handles), key=lambda t: t[0]))
    ax.legend(handles, labels)
    

    This is just a simple adaptation from the code listed at http://matplotlib.org/users/legend_guide.html

提交回复
热议问题