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

如何使用matplotlib绘制保持原始尺寸的水平对齐多图

matplotlib绘制水平对齐、保留原始尺寸多图的方案

要实现这个需求核心是避免matplotlib默认的子图尺寸自动缩放逻辑,需要提前根据所有图像的原始像素尺寸计算画布总大小,再按原始比例逐个放置子图,具体实现步骤和代码如下:

  • 先统一所有图像的dpi参数,屏幕显示默认用72dpi即可,打印场景可设置为300dpi
  • 计算所有图像的宽度总和、最大高度,加上预留的子图间距得到总画布的像素尺寸,再转成matplotlib要求的英寸单位(像素值/dpi)
  • 逐个添加子图时严格匹配每张图的原始宽高比例,设置aspect='equal'保证像素比例不变,关闭坐标轴避免额外留白

示例代码:

import matplotlib.pyplot as plt
import numpy as np
from PIL import Image

# 替换为你自己的图像读取逻辑,这里用随机数组模拟不同尺寸的图像
img1 = np.random.randint(0, 255, size=(400, 300, 3), dtype=np.uint8) # 高400px,宽300px
img2 = np.random.randint(0, 255, size=(300, 500, 3), dtype=np.uint8) # 高300px,宽500px
img3 = np.random.randint(0, 255, size=(450, 200, 3), dtype=np.uint8) # 高450px,宽200px
img_list = [img1, img2, img3]

# 基础参数配置
dpi = 72
h_space = 20 # 子图之间的水平间距,单位为像素,不需要间距可设为0

# 计算画布总尺寸
heights = [img.shape[0] for img in img_list]
widths = [img.shape[1] for img in img_list]
total_width = sum(widths) + h_space * (len(img_list) - 1)
max_height = max(heights)

# 创建指定尺寸的画布
fig = plt.figure(figsize=(total_width / dpi, max_height / dpi), dpi=dpi)

# 逐个放置子图
current_x = 0
for img in img_list:
    h, w = img.shape[:2]
    # 顶部对齐逻辑,要居中对齐的话把bottom改为 (max_height - h) / 2 / max_height
    bottom = (max_height - h) / max_height
    # add_axes参数为[左边界比例, 下边界比例, 宽度比例, 高度比例],均相对于总画布
    ax = fig.add_axes([current_x / total_width, bottom, w / total_width, h / max_height])
    ax.imshow(img, aspect='equal')
    ax.axis('off') # 关闭坐标轴避免占用额外空间
    current_x += w + h_space

plt.show()
# 保存图像时关闭额外留白
# plt.savefig("拼接结果.png", dpi=dpi, bbox_inches='tight', pad_inches=0)

如果你需要子图底部对齐,把bottom参数设为0即可。如果是灰度图像,在imshow里补充cmap='gray'参数即可正常显示。

内容的提问来源于stack exchange,提问作者Aymeric Leboucher

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 04:36:06