Mig*_*uel 6 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')
Run Code Online (Sandbox Code Playgroud)
如何只拥有'Boats'且'Cars'只出现一次?
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)
Run Code Online (Sandbox Code Playgroud)
我更喜欢使用性能更快、书写更紧凑的 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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2850 次 |
| 最近记录: |