-
先看效果
-
導入支持包
import matplotlib import matplotlib.pyplot as plt import numpy as np
-
生成測試數據
x = np.linspace(-3, 3, 50) y1 = 2 * x + 1 y2 = x ** 2
-
畫圖並設置圖例
# 寫法一:畫圖並設置圖例,label值爲圖例內容 plt.plot(x, y1, label='linear line') # 其中label爲圖例中對該plot的說明內容 plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--', label='square line') plt.legend(loc=4) # 設置圖例的放置位置 ''' **loc=4** 或 **loc='lower right'** 'best': 0, 'upper right': 1, 'upper left': 2, 'lower left': 3, 'lower right': 4, 'right': 5, 'center left': 6, 'center right': 7, 'lower center': 8, 'upper center': 9, 'center': 10, ''' # 寫法二:先畫圖,後面一併設置圖例,注意變量的寫法,需要加一個逗號‘,’ # l1, = plt.plot(x, y1) # l2, = plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--') # plt.legend(handles=[l1, l2], labels=['label1', 'label2'], loc='best')
-
出圖
plt.show()
效果如文首圖所示
-
說明
按順序複製程序即可執行
-
參考文獻
程序主要來自 Legend 圖例,略有改動
Matplotlib顯示圖例
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.