You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Matplotlib多子图每组图像对底部居中显示匹配/不匹配标签

你可以通过调整GridSpec的间距,并为每对图像单独添加底部居中标签实现需求,调整后的代码如下,关键修改点已标注:

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

# 从训练集中随机取4组样本
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.3)

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])
        
        # 展示图像
        ax.imshow(random_pairs[i][j])

        ax.set_xticks([])
        ax.set_yticks([])
        fig.add_subplot(ax)
    
    # ========== 新增标签展示逻辑 ==========
    # 将标注值转换为对应文本,这里假设距离为0代表同类别(match),可根据自己的标注规则调整
    label = "match" if random_distance[i] == 0 else "mismatch"
    # 获取当前图像对的外层网格位置
    outer_pos = outer[i].get_position(fig)
    # 计算底部居中坐标添加文本
    fig.text(
        (outer_pos.x0 + outer_pos.x1)/2, # 水平居中对齐
        outer_pos.y0 - 0.03, # 位置在当前图像对底部下方,可调整数值修改高低
        label,
        size=24,
        ha='center',
        va='top',
        color='black' # 可自定义颜色
    )

plt.show()

如果标签位置不符合预期,可以调整outer_pos.y0 - 0.03里的数值,数值越小标签越靠下;标注的判断逻辑也可以根据你自己的train_distance定义修改,比如标注1代表同类别就把判断条件改为random_distance[i] == 1。

内容的提问来源于stack exchange,提问作者Mohamed abdelmagid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 05:57:04