我們可以使用 pyplot 中的 subplot() 和 subplots() 方法來(lái)繪制多個(gè)子圖。
subplot() 方法在繪圖時(shí)需要指定位置,subplots() 方法可以一次生成多個(gè),在調(diào)用時(shí)只需要調(diào)用生成對(duì)象的 ax 即可。
subplot(nrows, ncols, index, **kwargs) subplot(pos, **kwargs) subplot(**kwargs) subplot(ax)
以上函數(shù)將整個(gè)繪圖區(qū)域分成 nrows 行和 ncols 列,然后從左到右,從上到下的順序?qū)γ總€(gè)子區(qū)域進(jìn)行編號(hào) 1...N ,左上的子區(qū)域的編號(hào)為 1、右下的區(qū)域編號(hào)為 N,編號(hào)可以通過(guò)參數(shù) index 來(lái)設(shè)置。
設(shè)置 numRows = 1,numCols = 2,就是將圖表繪制成 1x2 的圖片區(qū)域, 對(duì)應(yīng)的坐標(biāo)為:
(1, 1), (1, 2)
plotNum = 1, 表示的坐標(biāo)為(1, 1), 即第一行第一列的子圖。
plotNum = 2, 表示的坐標(biāo)為(1, 2), 即第一行第二列的子圖。
import matplotlib.pyplot as plt
import numpy as np
#plot 1:
xpoints = np.array([0, 6])
ypoints = np.array([0, 100])
plt.subplot(1, 2, 1)
plt.plot(xpoints,ypoints)
plt.title("plot 1")
#plot 2:
x = np.array([1, 2, 3, 4])
y = np.array([1, 4, 9, 16])
plt.subplot(1, 2, 2)
plt.plot(x,y)
plt.title("plot 2")
plt.suptitle("W3Cschool subplot Test")
plt.show()
顯示結(jié)果如下:
設(shè)置 numRows = 2,numCols = 2,就是將圖表繪制成 2x2 的圖片區(qū)域, 對(duì)應(yīng)的坐標(biāo)為:
(1, 1), (1, 2) (2, 1), (2, 2)
plotNum = 1, 表示的坐標(biāo)為(1, 1), 即第一行第一列的子圖。
plotNum = 2, 表示的坐標(biāo)為(1, 2), 即第一行第二列的子圖。
plotNum = 3, 表示的坐標(biāo)為(2, 1), 即第二行第一列的子圖。
plotNum = 4, 表示的坐標(biāo)為(2, 2), 即第二行第二列的子圖。
import matplotlib.pyplot as plt
import numpy as np
#plot 1:
x = np.array([0, 6])
y = np.array([0, 100])
plt.subplot(2, 2, 1)
plt.plot(x,y)
plt.title("plot 1")
#plot 2:
x = np.array([1, 2, 3, 4])
y = np.array([1, 4, 9, 16])
plt.subplot(2, 2, 2)
plt.plot(x,y)
plt.title("plot 2")
#plot 3:
x = np.array([1, 2, 3, 4])
y = np.array([3, 5, 7, 9])
plt.subplot(2, 2, 3)
plt.plot(x,y)
plt.title("plot 3")
#plot 4:
x = np.array([1, 2, 3, 4])
y = np.array([4, 5, 6, 7])
plt.subplot(2, 2, 4)
plt.plot(x,y)
plt.title("plot 4")
plt.suptitle("W3Cschool subplot Test")
plt.show()
顯示結(jié)果如下:
subplots() 方法語(yǔ)法格式如下:
matplotlib.pyplot.subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw)參數(shù)說(shuō)明:
import matplotlib.pyplot as plt
import numpy as np
# 創(chuàng)建一些測(cè)試數(shù)據(jù) -- 圖1
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
# 創(chuàng)建一個(gè)畫(huà)像和子圖 -- 圖2
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')
# 創(chuàng)建兩個(gè)子圖 -- 圖3
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)
# 創(chuàng)建四個(gè)子圖 -- 圖4
fig, axs = plt.subplots(2, 2, subplot_kw=dict(projection="polar"))
axs[0, 0].plot(x, y)
axs[1, 1].scatter(x, y)
# 共享 x 軸
plt.subplots(2, 2, sharex='col')
# 共享 y 軸
plt.subplots(2, 2, sharey='row')
# 共享 x 軸和 y 軸
plt.subplots(2, 2, sharex='all', sharey='all')
# 這個(gè)也是共享 x 軸和 y 軸
plt.subplots(2, 2, sharex=True, sharey=True)
# 創(chuàng)建標(biāo)識(shí)為 10 的圖,已經(jīng)存在的則刪除
fig, ax = plt.subplots(num=10, clear=True)
plt.show()
部分圖表顯示結(jié)果如下:
圖1
圖2
圖3
圖4
更多建議: