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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With