新聞中心
在Python的數(shù)據(jù)可視化庫(kù)Matplotlib中,subplot是一個(gè)非常重要的函數(shù),它允許我們?cè)谕粋€(gè)圖像窗口中創(chuàng)建多個(gè)子圖,這在對(duì)比不同數(shù)據(jù)或者展示數(shù)據(jù)的不同方面時(shí)非常有用。

創(chuàng)新互聯(lián)是一家專業(yè)提供新河企業(yè)網(wǎng)站建設(shè),專注與成都網(wǎng)站設(shè)計(jì)、成都網(wǎng)站建設(shè)、H5網(wǎng)站設(shè)計(jì)、小程序制作等業(yè)務(wù)。10年已為新河眾多企業(yè)、政府機(jī)構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)的建站公司優(yōu)惠進(jìn)行中。
subplot的基本語(yǔ)法是:
fig.add_subplot(nrows, ncols, index)
nrows和ncols定義了子圖網(wǎng)格的行數(shù)和列數(shù),index則是子圖的編號(hào),編號(hào)的順序是從左到右,從上到下。
下面是一個(gè)簡(jiǎn)單的例子,展示了如何使用subplot創(chuàng)建2×2的子圖網(wǎng)格:
import matplotlib.pyplot as plt
import numpy as np
創(chuàng)建數(shù)據(jù)
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)
創(chuàng)建一個(gè)2x2的子圖網(wǎng)格
fig, axs = plt.subplots(2, 2)
fig.suptitle('Vertically stacked subplots')
在第一個(gè)子圖中繪制正弦曲線
axs[0, 0].plot(x, y)
axs[0, 0].set_title('Axis [0, 0]')
在第二個(gè)子圖中繪制余弦曲線
axs[0, 1].plot(x, np.cos(x), 'tab:orange')
axs[0, 1].set_title('Axis [0, 1]')
在第三個(gè)子圖中繪制正切曲線
axs[1, 0].plot(x, np.tan(x), 'tab:green')
axs[1, 0].set_title('Axis [1, 0]')
在第四個(gè)子圖中繪制正弦曲線的平方
axs[1, 1].plot(x, y ** 2, 'tab:red')
axs[1, 1].set_title('Axis [1, 1]')
for ax in axs.flat:
ax.set(xlabel='xlabel', ylabel='ylabel')
Hide x labels and tick labels for top plots and y ticks for right plots.
for ax in axs.flat:
ax.label_outer()
plt.show()
在這個(gè)例子中,我們首先導(dǎo)入了必要的庫(kù),然后創(chuàng)建了一些數(shù)據(jù),我們使用plt.subplots函數(shù)創(chuàng)建了一個(gè)2×2的子圖網(wǎng)格,并給每個(gè)子圖分配了一個(gè)Axes對(duì)象,我們?cè)诿總€(gè)子圖中繪制了不同的曲線,并設(shè)置了標(biāo)題,我們隱藏了頂部和右側(cè)的標(biāo)簽,以便更好地查看每個(gè)子圖。
這就是subplot的基本用法,當(dāng)然,你還可以通過(guò)調(diào)整nrows,ncols和index的值,來(lái)創(chuàng)建不同大小和形狀的子圖網(wǎng)格,你還可以使用plt.subplot函數(shù),直接在當(dāng)前的Figure對(duì)象上添加子圖。
subplot是一個(gè)非常強(qiáng)大的工具,可以幫助你更好地展示和比較數(shù)據(jù),希望這個(gè)教程能幫助你理解subplot的用法,如果你有任何問(wèn)題,歡迎隨時(shí)向我提問(wèn)。
當(dāng)前題目:pythonsubplots_adjust
轉(zhuǎn)載來(lái)源:http://fisionsoft.com.cn/article/djephje.html


咨詢
建站咨詢
