matplotlib中plt.legend等的使用方法


plt.lengend()

用於給圖像加圖例。

圖例是集中於地圖一角或一側的地圖上各種符號和顏色所代表內容與指標的說明,有助於更好的認識地圖。

語法參數如下: matplotlib.pyplot.legend(*args, **kwargs)

keyword Description
loc Location code string, or tuple (see below).圖例所有figure位置
prop the font property字體參數
fontsize the font size (used only if prop is not specified)
markerscale the relative size of legend markers vs. original
圖例標記與原始標記的相對大小
markerfirst If True (default), marker is to left of the label.
如果為True,則圖例標記位於圖例標簽的左側
numpoints the number of points in the legend for line
為線條圖圖例條目創建的標記點數
scatterpoints the number of points in the legend for scatter plot
為散點圖圖例條目創建的標記點數
scatteryoffsets a list of yoffsets for scatter symbols in legend
為散點圖圖例條目創建的標記的垂直偏移量
frameon If True, draw the legend on a patch (frame).
控制是否應在圖例周圍繪制框架
fancybox If True, draw the frame with a round fancybox.
控制是否應在構成圖例背景的FancyBboxPatch周圍啟用圓邊
shadow If True, draw a shadow behind legend.
控制是否在圖例后面畫一個陰
framealpha Transparency of the frame.
控制圖例框架的 Alpha 透明度
edgecolor Frame edgecolor.
facecolor Frame facecolor.
ncol number of columns 設置圖例分為n列展示
borderpad the fractional whitespace inside the legend border
圖例邊框的內邊距
labelspacing the vertical space between the legend entries
圖例條目之間的垂直間距
handlelength the length of the legend handles 
圖例句柄的長度
handleheight the height of the legend handles 
圖例句柄的高度
handletextpad the pad between the legend handle and text 
圖例句柄和文本之間的間距
borderaxespad the pad between the axes and legend border
軸與圖例邊框之間的距離
columnspacing the spacing between columns 列間距
title the legend title
bbox_to_anchor the bbox that the legend will be anchored.指定圖例在軸的位置
bbox_transform the transform for the bbox. transAxes if None.

常用的幾個參數:

(1)設置圖列位置

plt.legend(loc='upper center')

0: ‘best'
1: ‘upper right'
2: ‘upper left'
3: ‘lower left'
4: ‘lower right'
5: ‘right'
6: ‘center left'
7: ‘center right'
8: ‘lower center'
9: ‘upper center'
10: ‘center'

(2)設置圖例字體大小

fontsize : int or float or {‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’}

(3)設置圖例邊框及背景

plt.legend(loc='best',frameon=False) #去掉圖例邊框
plt.legend(loc='best',edgecolor='blue') #設置圖例邊框顏色
plt.legend(loc='best',facecolor='blue') #設置圖例背景顏色,若無邊框,參數無效

對於邊框還可以采用面向對象方式:

legend = plt.legend(["First", "Second"])
frame = legend.get_frame()
frame.set_facecolor('blue')

(4)設置圖例標題

legend = plt.legend(["CH", "US"], title='China VS Us')

(5)設置圖例名字及對應關系

legend = plt.legend([p1, p2], ["CH", "US"])

from matplotlib import pyplot as plt
import numpy as np
 
train_x = np.linspace(-1, 1, 100)
train_y_1 = 2*train_x + np.random.rand(*train_x.shape)*0.3
train_y_2 = train_x**2+np.random.randn(*train_x.shape)*0.3
 
p1 = plt.scatter(train_x, train_y_1, c='red', marker='v' )
p2= plt.scatter(train_x, train_y_2, c='blue', marker='o' )
legend = plt.legend([p1, p2], ["CH", "US"], facecolor='blue')

plt.show()

plt.scatter()

用於畫散點圖。

x,y X和Y是長度相同的數組
s size,點的大小,標量或與數據長度相同的數組
c color,點的顏色,標量或與數據長度相同的數組
marker MarketStyle,可選,點的形狀,默認'o'
cmap Colormap,可選,默認'None'
norm Normalize,亮度設置,0-1
vmin,vmax 亮度設置
alpha 透明度,0-1
linewidths  

其中散點的形狀參數marker如下:

其中顏色參數c如下:

scatter(x, y, 點的大小, 顏色,標記),這是最主要的幾個用法,如果括號中不寫s=  c=則按默認順序,寫了則按規定的來,不考慮順序

import matplotlib.pyplot as plt 

#x,y,大小,顏色
plt.scatter([1,2,3,4],[2,4,6,8],[10,20,30,400],['r', 'b','y','k'])   
plt.scatter([1,2,3,4],[9,8,7,6],s=10,c='b', marker='v')   

plt.show()
import numpy as np
import matplotlib.pyplot as plt

# Fixing random state for reproducibility
np.random.seed(19680801)


N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = (30 * np.random.rand(N))**2  # 0 to 15 point radii

plt.scatter(x, y, s=area, c=colors, alpha=0.5)
plt.show()

plt.plot()

一個通用命令,將(x, y)繪制成線條或散點圖。

x, y 數據,x是可選的,默認range(len(y))
fmt format,格式,形狀,例如,'ro'表示紅圈
data 標有數據的對象,可選

其中,線條的格式還可以使用如下線屬性:

alpha float,透明度
fillstyle {'full', 'left', 'right', 'bottom', 'top', 'none'}
linestyle/ls {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
linewidth/lw float
marker marker style
markeredgecolor/mec color
markeredgewidth/mew float
markerfacecolor/mfc color
markersize/ms float
... ...

當線屬性與fmt沖突時,線屬性優先。

一些默認的寫法:

>>> plot(x, y)        # plot x and y using default line style and color
>>> plot(x, y, 'bo')  # plot x and y using blue circle markers
>>> plot(y)           # plot y using x as index array 0..N-1
>>> plot(y, 'r+')     # ditto, but with red plusses
import numpy as np
import matplotlib.pyplot as plt

X = np.linspace(0, 2*np.pi, 32, endpoint=True)
C,S = np.cos(X), np.sin(X)

#plt.plot(X,C)
#plt.plot(X,S)
plt.plot(X, C, 'go--')
plt.plot(X,S, color='green', marker='o', linestyle='dashed')
# 一個是fmt,一個是線屬性,但是它們的格式是一樣的

plt.show()

plt.figure()

用於創建一個新圖。

num 新圖的編號,默認遞增
figsize 寬度,高度,以英寸為單位
dpi 分辨率,整數
facecolor 背景顏色
edgecolor 邊框顏色
frameon 若為False,則沒有邊框
clear 若為True,如果圖的編號已存在則先清除

如果有多個figure,請顯示的調用 pyplot.close() 關閉你不需要使用的figure,以便pyplot能正確的清理內存。

import numpy as np
import matplotlib.pyplot as plt

X = np.linspace(0, 2*np.pi, 32, endpoint=True)
C,S = np.cos(X), np.sin(X)

plt.figure(num=1)
plt.plot(X,C)
#plt.close()

plt.figure(2)
plt.plot(X,S)

plt.figure(3)
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])

plt.show()

會連續展現三張圖,注意與下面subplot的區別。

對於只有一張圖時,也有作用,例如設置尺寸和分辨率等:

# 創建一個8x6大小的figure,並設置每英寸80個像素點
plt.figure(figsize=(8, 6), dpi=80)

plt.subplot()

用於在一個Figure對象里畫多個子圖(Axes)。

其調用格式:subplot(numRows, numCols, plotNum),即(行、列、序號)。

圖表的整個繪圖區域被分成numRows行和numCols列,plotNum參數指定創建的Axes對象所在的區域(左上角序號為1)

如果行數、列數和序號都是個位數可以簡寫成一個整數,否則需要用逗號隔開。

import numpy as np
import matplotlib.pyplot as plt

X = np.linspace(0, 2*np.pi, 32, endpoint=True)
C,S = np.cos(X), np.sin(X)

plt.subplot(221)
plt.plot(X,C)

plt.subplot(2,2,2) #可以隔開,也可以不隔開
plt.plot(X,S)

plt.subplot(212)
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])

plt.show()

 

 

參考鏈接:

1. CSDN開碼牛-matplotlib命令與格式:圖例legend語法及設置

2. CSDNweixin_41950276-plt.legend( )函數,給圖像加上圖例

3. matplotlib.pyplot.legend官方文檔

4. CSDNxiaodaicai4452-python繪圖基礎—scatter用法

5. matplotlib.pyplot.scatter官方文檔

6. matplotlib.pyplot.plot官方文檔

7. matplotlib.pyplot.figure官方文檔

8. CSND繁小華-matplotlib繪制多個子圖——subplot


免責聲明!

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



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