8

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?

Miguel
  • 1,293
  • 1
  • 13
  • 30

2 Answers2

9
    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)
Miguel
  • 1,293
  • 1
  • 13
  • 30
6

I prefer to use the numpy functions which are faster in performance and more compact writting.

import numpy as np
import matplotlib.pyplot as plt

fig,ax = plt.subplots(figsize=(7.5,7.5))

X = np.arange(10)

for i in range(5):
    Y1=np.random.uniform(low=0.0,high=1.0,size=(10))    #boatarrays[i]
    Y2=np.random.uniform(low=0.0,high=1.0,size=(10))    #cararrays[i]
    ax.plot(X,Y1,color='r',label='Boats')
    ax.plot(X,Y2,color='b',label='Cars')

hand, labl = ax.get_legend_handles_labels()
plt.legend(np.unique(labl))
plt.tight_layout()
plt.show()
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
iblasi
  • 1,269
  • 9
  • 21