matplotlib的使用——legend圖例的設置


圖例設置常用函數及其作用

plt.legend()

plt.legend(
	*args,
	**kwargs)

其中**kwargs包含常用的參數:
1、loc:圖例位置,可取:‘best’、 ‘upper right’、‘upper left’、‘lower left’、‘lower right’、‘right’、‘center left’、‘center’、'right’、‘lower center’、‘upper center’、‘center’) 。
圖片來自官網:

在這里插入圖片描述

2、borderpad:圖例的內邊距 ,None或者float。
3、fontsize:int或float或{‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’},用於設置字體大小。
4、frameon: 是否顯示圖例邊框,None或者bool。
5、fancybox:是否將圖例框的邊角設為圓形,None或者bool。
6、framealpha:控制圖例框的透明度,None或者float。
7、ncol:圖例列的數量,默認為1。
8、title:圖例的標題
9、shadow: 是否為圖例邊框添加陰影,None或者bool。
10、markerfirst:bool量,True表示圖例標簽在句柄右側,false反之。
11、markerscale: 圖例標記為原圖的多少倍。
12、labelspacing:圖例中條目之間的距離,None或者float。
13、handlelength:圖例中句柄的長度。
14、handles:填寫用於添加到圖例里的線條。
15、labels:對應着添加到圖例里線條的標簽。
應用示例

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-1,1,50)
y1 = 2*x + 1
y2 = x**2

plt.figure(num=1,figsize=(8,5))
# 用於設置x軸的范圍
plt.xlim((-1,1))
# 用於設置y軸的范圍
plt.ylim((-2,5))
# 設置x軸的名稱
plt.xlabel('I am x label')
# 設置y軸的名稱
plt.ylabel('I am y label')
# 將新的x軸上的坐標設置為-1到1間隔數為10
newTicks = np.linspace(-1,1,10)
plt.xticks(newTicks)
# 將y軸坐標按照一定格式設置字符,-2對應really bad,-1對應little bad
plt.yticks([-2,-1.0,0,1.5,3], 
           ['really bad','little bad','normal','little good','pretty good'])
# 按照一定格式畫線
line1, = plt.plot(x,y2,color = 'red',linewidth = 1.0,linestyle = '--',label = 'curve')
line2, = plt.plot(x,y1,label = 'straight line')
# 設置圖例
plt.legend(loc = 'best', handles = [line1,line2,],labels = ['curve one','straight one'],
    shadow = True,
    fancybox = True,
    markerfirst = True,
    borderpad = 1.5,
    framealpha = 1,
    title = 'legend',
    labelspacing = 1.2)
plt.show() 

結果為:
在這里插入圖片描述


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM