subplots() + Axes
先上代碼
import numpy as np
import matplotlib.pyplot as plt
X_train = np.random.randn(25, 784) # 784 = 28 * 28
fig, ax = plt.subplots( # subplots()返回一個(gè)Figure,和一個(gè)或一組Axes
nrows=5, # 這里是返回5 * 5的Axes
ncols=5,
sharex=True, # 共享坐標(biāo)軸
sharey=True, )
i = 0
ax = ax.flatten() # flatten()將ax由5*5的Axes組展平成1*25的Axes組
for img in X_train: # 每一個(gè)img是1*784的張量
if i > 24:
break
img = img.reshape(28, 28) # 將img從1*784重構(gòu)成28*28的張量
ax[i].imshow(img, cmap='Greys', interpolation='nearest')
i += 1 # imshow()以圖片形式顯示
ax[0].set_xticks([]) # 設(shè)置需要顯示的坐標(biāo)標(biāo)記,例如方括號(hào)可填[1,10,20]
ax[0].set_yticks([]) # 此時(shí)坐標(biāo)軸上1,10,20的位置就會(huì)顯示標(biāo)記
plt.tight_layout() # tight_layout()使得Figure上的Axes緊密排列,留出的空白少
plt.show()
- 點(diǎn)擊查看matplotlib.axes.Axes.imshow()詳情
- 另一種方式
import matplotlib.pyplot as plt
import numpy as np
fig, axs = plt.subplots(2, 2) # axs為2*2的Axes組
axs[0, 0].imshow(np.random.random((100, 100)))
axs[0, 1].imshow(np.random.random((100, 100)))
axs[1, 0].imshow(np.random.random((100, 100)))
axs[1, 1].imshow(np.random.random((100, 100)))
plt.subplot_tool() # subplot_tool()是調(diào)節(jié)Axes顯示的工具
plt.show()