Legend 圖例
在Matplotlib中繪制多個圖線時,需要在圖表中說明每條曲線的含義,這時就用到了圖例Legend。
使用方法
- 在
plt.plot中添加label屬性(不添加也可,但是需要在plt.legend中添加) - 在
plt.plot之后添加plt.legend(handles=,labels=,loc=)
相應參數及注意事項
plt.legend(handles=,labels=,loc=)
-
loc,缺省為'best''best'自動選擇最空白的位置,並會隨着圖像大小變化調整位置'upper right''upper left''center right''center left''lower right''lower left'
-
handles
是列表類型,傳入需要標注的圖線對象
line1, = plt.plot(x,y,color='blue',label='hello')
line2 = plt.plot(x,y2,color='red')
plt.legend(handles=[line1])

缺省為所有的圖線對象
注意:圖線對象后必須有逗號,如line1,=...
labels
是列表類型,傳入對應於handles中圖線的label,會覆蓋掉plt.plot中的label
代碼實例及運行結果
from matplotlib import pyplot as plt
import numpy as np
#1、參數
x = np.linspace(-1,2,50)
y1 = 2*x
y2 = x**2
#2、設置區間
plt.xlim((-1,2))
plt.ylim((-2,3))
#3、設置坐標軸標簽
plt.xlabel('I am x')
plt.ylabel('I am y')
#4、設置坐標軸的單位長度
x_ticks = np.linspace(-1,2,9)
plt.xticks(x_ticks)
plt.yticks([-2,-1,0,2,4],[r'$very\ bad$',r'$bad$',r'$plain$',r'$very\ good$',r'$\alpha$'])
#5、繪制圖線,注意label屬性用於后面生成圖例
line1, = plt.plot(x,y1,color='r',linestyle='--',label='up')
line2, = plt.plot(x,y2,label='down')
#6、生成圖例
plt.legend(handles=[line1,line2],labels=['bbb','aaa'])
plt.show()

