删除matplotlib图例中的重复标签

时间:2015-10-29 21:07:50

标签: matplotlib legend-properties

如果使用matplotlib绘制多条线或点,有时您可能会发现有重复标签的情况。例如:

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')

如何只让'Boats''Cars'出现一次?

2 个答案:

答案 0 :(得分:1)

    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)

答案 1 :(得分:0)

我更喜欢使用性能更快,写入更紧凑的numpy函数。

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()