Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove repeated lables in matplotlib legend [duplicate]

If you plot several lines or points with matplotlib, sometimes you might find a situation where you will have repeated lables. For example:

for i in range(5):
    Y1=boatarrays[i]
    Y2=cararrays[i]
    ax.plot(X,Y1,color='r',label='Boats')
    ax.plot(X,Y2,color='b',label='Cars')

How to only have 'Boats' and 'Cars' only appear once?

like image 575
Miguel Avatar asked Oct 29 '15 21:10

Miguel


1 Answers

    import matplotlib.pyplot as plt
    #Prepare fig
    fig = plt.figure()
    ax  = fig.add_subplot(111)
    for i in range(5):
        Y1=boatarrays[i]
        Y2=carsarrays[i]
        ax.plot(X,Y1,color='r',label='Boats')
        ax.plot(X,Y2,color='b',label='Cars')
    #Fix legend
    hand, labl = ax.get_legend_handles_labels()
    handout=[]
    lablout=[]
    for h,l in zip(hand,labl):
       if l not in lablout:
            lablout.append(l)
            handout.append(h)
    fig.legend(handout, lablout)
like image 154
Miguel Avatar answered Oct 31 '22 13:10

Miguel