[Python] How is order of items in matplotlib legend determined?

Discussão em 'Python' iniciado por Stack, Março 29, 2025.

  1. Stack

    Stack Membro Participativo

    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,color='r',label='Top',alpha=.1))
    h1=ax.bar(1,2,label='Middle')
    hb=ax.add_patch(Rectangle((1,1),1,1,color='k',label='Bottom',alpha=.11))
    legend()
    show()


    and end up with Bottom above Middle. How can I get the right order? Is it not determined by creation order?

    [​IMG]

    Update: The following can be used to force the order. I think this may be the simplest way to do it, and that seems awkward. The question is what determines the original order?

    hh=[ht,h1,hb]
    legend([ht,h1.patches[0],hb],[H.get_label() for H in hh])

    Continue reading...

Compartilhe esta Página