Matplotlib.pyplot绘制子图


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()返回一个Figure,和一个或一组Axes
    nrows=5,                       # 这里是返回5 * 5的Axes
    ncols=5,
    sharex=True,                   # 共享坐标轴
    sharey=True, )

i = 0
ax = ax.flatten()                  # flatten()将ax由5*5的Axes组展平成1*25的Axes组
for img in X_train:                # 每一个img是1*784的张量
  if i > 24:
    break
  img = img.reshape(28, 28)        # 将img从1*784重构成28*28的张量
  ax[i].imshow(img, cmap='Greys', interpolation='nearest')
  i += 1                           # imshow()以图片形式显示


ax[0].set_xticks([])               # 设置需要显示的坐标标记,例如方括号可填[1,10,20]
ax[0].set_yticks([])               # 此时坐标轴上1,10,20的位置就会显示标记
plt.tight_layout()                 # tight_layout()使得Figure上的Axes紧密排列,留出的空白少
plt.show()
  • 点击查看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()是调节Axes显示的工具
plt.show()

你可能感兴趣的:(Matplotlib.pyplot绘制子图)