在 matplotlib 中为多个子图设置标题

set a title for multiple subplots in matplotlib

我有一个图像数据集,每条记录包含 2 张图像,如果它们相同 class 或不同(从 Fashion MNIST 数据集构建)。

我想在每对上显示标签(“匹配”或“不匹配”)。 到目前为止我的输出如下:

我的代码:

%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

# pick 4 random pairs from the training set
random_indices = np.random.randint(0, len(train_pairs), size=4)
random_pairs = train_pairs[random_indices]
random_distance = train_distance[random_indices]

fig = plt.figure(figsize=(20, 10))
outer = gridspec.GridSpec(2, 2, wspace=0.2, hspace=0.2)

for i in range(4):
  inner = gridspec.GridSpecFromSubplotSpec(1, 2,
                  subplot_spec=outer[i], wspace=0.1, hspace=0.1)

  for j in range(2):
    ax = plt.Subplot(fig, inner[j])
    
    # show the image
    ax.imshow(random_pairs[i][j])

    # show the label
    ax.text(0, 0, '{}'.format(random_distance[i]),
            size=24, ha='center', va='center', color='w')

    ax.set_xticks([])
    ax.set_yticks([])
    fig.add_subplot(ax)

fig.show()

我想要的是在每对图像之间的底部中心位置显示标签“匹配”或“不匹配”。

我尝试使用子图,它给出了所需的结果,对每个子图使用 supxlabel

%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

# pick 4 random pairs from the training set
random_indices = np.random.randint(0, len(train_pairs), size=4)
random_pairs = train_pairs[random_indices]
random_distance = train_distance[random_indices]

fig = plt.figure(figsize=(20, 10))

subFigs = fig.subfigures(2, 2).flatten()
print(subFigs)

for i in range(4):
  subFig = subFigs[i]
  label = "Match" if random_distance[i] else "miss-Match"
  subFig.supxlabel(label, fontsize=16, color='red')

  axs = subFig.subplots(1, 2)

  for j in range(2):
    ax = axs[j]
    
    # show the image
    ax.imshow(random_pairs[i][j])

    ax.set_xticks([])
    ax.set_yticks([])
    subFig.add_subplot(ax)

fig.show()

得到的结果: