一、ax.legend參數
在matplotlib中,ax.legend()函數主要用於為圖形添加圖例。在傳遞參數時,我們可以使用一系列關鍵字參數來定製圖例的位置,大小,字體等屬性。以下是ax.legend()支持的常用參數:
參數名 類型 說明 loc string 指定圖例的位置 bbox_to_anchor tuple 指定圖例的錨點(外部邊界或圖表頂部左上) ncol int 指定圖例的列數 fontsize int 指定圖例的字體大小 title string 圖例的標題 frame_on bool 是否顯示圖例的邊框 shadow bool 是否顯示圖例的陰影 fancybox bool 是否為圖例的邊框添加圓角 framealpha float 圖例的邊框透明度
其中,loc參數可以指定圖例在哪個位置出現。它可以採用一個字元串,表示需要顯示圖例的位置,如’upper right’、’lower left’等。另外,loc參數也可以接收一個長度為2的元組來指定圖例的位置。例如,(0.5, 0.5)表示圖例的位置位於圖形區域的中心。
二、ax.legend設置邊框粗細
ax.legend()函數中的frame_linewidth參數用於設置圖例邊框的粗細程度。frame_linewidth參數需要指定一個浮點數來表示邊框的粗細程度,例如:
import matplotlib.pyplot as plt plt.style.use('ggplot') fig, ax = plt.subplots() ax.plot([1, 2, 3], [2, 4, 6], label='line 1') ax.plot([1, 2, 3], [1, 3, 5], label='line 2') legend = ax.legend(loc='upper center', frame_linewidth=2)
在上述代碼中,我們將frame_linewidth參數設置為2,表示圖例邊框的粗細為2個單位。圖例將會位於圖表的中上方。
三、ax.legend設置邊框顏色
在matplotlib中,ax.legend()函數中的frame_color參數用於指定圖例邊框的顏色。
import matplotlib.pyplot as plt plt.style.use('ggplot') fig, ax = plt.subplots() ax.plot([1, 2, 3], [2, 4, 6], label='line 1') ax.plot([1, 2, 3], [1, 3, 5], label='line 2') legend = ax.legend(loc='upper center', frame_color='red')
上述代碼中,我們將frame_color參數設置為’red’,表示圖例邊框的顏色為紅色。圖例將會位於圖表的中上方。
四、ax.legend的字體大小
在matplotlib中,ax.legend()函數中的fontsize參數用於指定圖例的字體大小。fontsize參數需要指定一個整數來表示字體的大小,例如:
import matplotlib.pyplot as plt plt.style.use('ggplot') fig, ax = plt.subplots() ax.plot([1, 2, 3], [2, 4, 6], label='line 1') ax.plot([1, 2, 3], [1, 3, 5], label='line 2') legend = ax.legend(loc='upper center', fontsize=14)
在上述代碼中,我們將fontsize參數設置為14,表示圖例的字體大小為14個單位。圖例將會位於圖表的中上方。
五、ax.legend實例
import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Data x = np.linspace(-10, 10, 100) y1 = np.sin(x) y2 = np.cos(x) # Plot fig, ax = plt.subplots(figsize=(10,6)) ax.plot(x, y1, label='sin(x)', linewidth=2) ax.plot(x, y2, label='cos(x)', linewidth=2) # Legend legend = ax.legend(loc='upper center', shadow=True, fontsize=16) legend.get_frame().set_facecolor('#FFFFFF') # 設置圖例邊框顏色 plt.setp(legend.get_lines(), linewidth=4) # 設置標籤線寬 plt.show()
上述代碼中,我們生成了兩個曲線數據y1和y2,並分別用ax.plot()將它們繪製到了圖形上。隨後,我們通過ax.legend()函數為該圖形添加了一個圖例。圖例的位置位於圖表頂部中心,陰影效果開啟,字體大小為16。
在圖例的生成後,我們對其進行了一系列自定義設置:設置圖例邊框為白色,標籤線寬為4。
最終,我們調用plt.show()函數顯示該圖形。圖形的結果如下所示:
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/157814.html