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

Matplotlib拼接多图生成无白边PNG的实现方案

matplotlib多子图拼接无白边问题

核心需求

  • 输出PNG格式拼接图,所有子图之间无任何白色间隔,效果需适配任意列数(nb_col)、行数(nb_rows)配置
  • 现有问题:按自定义行列数排布子图时,垂直、水平方向总会出现白色条带,无法实现子图紧密贴合无白边,需要明确代码优化方向,以及相关API逻辑的理解偏差

初始测试代码

import matplotlib.pyplot as plt
import numpy as np

nb_rows = 3
nb_col = 7

fig = plt.figure(figsize=(7.4803, 9.0551))
a = np.random.random((100, 130))

for ind in range(0, nb_rows*nb_col):
    ax = fig.add_subplot(nb_rows, nb_col, ind+1)
    ax.imshow(a,
              interpolation="nearest",
              origin="lower",
              extent=[0, 100, 0, 130])
    ax.set_xticklabels([])
    ax.set_yticklabels([])
    ax.grid(False)
    ax.axis("off")

fig.subplots_adjust(left=0, right=1, bottom=0, top=1,
                        wspace=0, hspace=0)

fig.savefig('test.png', format="png", dpi=300, bbox_inches="tight")

EDIT1:子图比例验证测试

修改测试脚本,验证最终输出的子图是否保留原始矩阵尺寸比例(要求子图保持1:1.5的宽高比),修改后代码如下:

import matplotlib.pyplot as plt
import numpy as np

nb_rows = 3
nb_col = 7

fig = plt.figure(figsize=(7.4803, 9.0551))
#a = np.random.random((100, 13))


for ind in range(0, nb_rows*nb_col):
    ax = fig.add_subplot(nb_rows, nb_col, ind+1)
    if ind % 2 == 0:
        a = np.zeros((150,100))
    else:
        a = np.ones((150, 100))
   # a = np.zeros((150,100))
    ax.imshow(a,
              vmin=0, vmax=1, cmap="Greys_r",
              interpolation="nearest",
              origin="lower",
              extent=[0, 100, 0, 150],
              aspect='auto')
    ax.set_xticklabels([])
    ax.set_yticklabels([])
    ax.grid(False)
    ax.axis("off")

fig.subplots_adjust(left=0, right=1, bottom=0, top=1,
                        wspace=0, hspace=0)

fig.savefig('test.png', format="png", dpi=300, bbox_inches="tight")

测试结论:imshow()中设置aspect='auto'会丢失子图原始1:1.5的宽高比例。

EDIT2:ImageGrid方案测试

测试发现ImageGrid组件可初步实现无间隔需求,基于原有逻辑适配的简化版示例代码如下:

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid1 import ImageGrid

nb_rows = 2
nb_col = 2

fig = plt.figure(figsize=(7.4803, 9.0551))


grid = ImageGrid(fig, 111,
                 nrows_ncols=(nb_rows, nb_col),
                 axes_pad=0,
                 )
ind=0

for ax in grid:
    if ind % 2 == 0:
        a = np.zeros((150,100))
    else:
        a = np.ones((150, 100))

    ind +=1

    ax.imshow(a,
              vmin=0, vmax=1, cmap="Greys_r",
              interpolation="nearest",
              origin="lower",
              extent=[0, 100, 0, 150],
              aspect='auto')
    ax.set_xticklabels([])
    ax.set_yticklabels([])
    ax.grid(False)
    ax.axis("off")

fig.savefig('test3.png', format="png", dpi=300, bbox_inches="tight")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 15:27:17