App下載

Matplotlib的subplot和subplots有什么區(qū)別?簡單對比!

猿友 2021-07-30 14:00:09 瀏覽數(shù) (3008)
反饋

在之前的文章中小編介紹過subplot可以畫子圖。但是matplotlib繪制子圖的方式不止一種,subplots也可以畫子圖。因?yàn)閟ubplots介紹比較少,小編打算進(jìn)行一個(gè)對比,各位小伙伴可以看看這兩個(gè)方法是否功能一致。

對比開始:

需求:畫出兩張子圖,在一行顯示,子圖中的內(nèi)容一模一樣

subplot代碼:

ax1 = plt.subplot(1,2,1)
ax1.scatter(positive['X1'], positive['X2'], s=50, marker='x', label='Positive')
ax1.scatter(negative['X1'], negative['X2'], s=50, marker='o', label='Negative')
ax1.legend()#添加圖列就是右上角的點(diǎn)說明
ax2 = plt.subplot(1,2,2)
ax2.scatter(positive['X1'], positive['X2'], s=50, marker='x', label='Positive')
ax2.scatter(negative['X1'], negative['X2'], s=50, marker='o', label='Negative')
ax2.legend()#添加圖列就是右上角的點(diǎn)說明

 

運(yùn)行結(jié)果

subplots代碼

fig, ax = plt.subplots(figsize=(12,8),ncols=2,nrows=1)#該方法會返回畫圖對象和坐標(biāo)對象ax,figsize是設(shè)置子圖長寬(1200,800)
ax[0].scatter(positive['X1'], positive['X2'], s=50, marker='x', label='Positive')
ax[0].scatter(negative['X1'], negative['X2'], s=50, marker='o', label='Negative')
ax[0].legend()#添加圖列就是右上角的點(diǎn)說明
ax[1].scatter(positive['X1'], positive['X2'], s=50, marker='x', label='Positive')
ax[1].scatter(negative['X1'], negative['X2'], s=50, marker='o', label='Negative')
ax[1].legend()#添加圖列就是右上角的點(diǎn)說明

運(yùn)行結(jié)果

對比結(jié)果:

可以看出來兩者都可以實(shí)現(xiàn)畫子圖功能,只不過subplots幫我們把畫板規(guī)劃好了,返回一個(gè)坐標(biāo)數(shù)組對象,而subplot每次只能返回一個(gè)坐標(biāo)對象,subplots可以直接指定畫板的大小。

到此subplot和subplots區(qū)別在哪相信小伙伴心里已經(jīng)清楚了,更多Matplotlib 使用介紹的文章可以繼續(xù)關(guān)注W3Cschool后續(xù)的內(nèi)容。

0 人點(diǎn)贊