在matplotlib图例中删除重复标签

9
如果您使用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个回答

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)

7

我更喜欢使用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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接