如何按每行3张格式垂直拼接并保存多张Matplotlib图像?
解决多行多图(每行3张)垂直拼接保存问题
问题分析
原代码存在两个核心问题:
- 硬编码按每行2张处理,不符合每行3张的需求
- 行内图像拼接使用了
axis=0(垂直方向拼接),导致所有图像被纵向连成单行,而非横向组成每行后再纵向拼接
修改后的代码
def save_macro_figures(self): num_figures = len(gv.figures) cols = 3 # 指定每行3张布局 # 计算总行数:向上取整,自动兼容奇偶数量 rows = (num_figures + cols - 1) // cols macro_rows = [] # 空图像列表直接返回,避免报错 if num_figures == 0: return # 获取单张图像的尺寸(假设所有图像尺寸一致) sample_img = np.array(gv.figures[0].canvas.renderer.buffer_rgba()) img_height, img_width, img_channels = sample_img.shape for i in range(rows): # 提取当前行的图像切片 start_idx = i * cols end_idx = start_idx + cols row_figures = gv.figures[start_idx:end_idx] # 转换为numpy数组格式 row_imgs = [np.array(fig.canvas.renderer.buffer_rgba()) for fig in row_figures] # 处理最后一行图像不足3张的情况:补空白透明图像对齐宽度 while len(row_imgs) < cols: blank_img = np.zeros((img_height, img_width, img_channels), dtype=np.uint8) row_imgs.append(blank_img) # 行内图像横向拼接(axis=1为水平方向) row_concat = np.concatenate(row_imgs, axis=1) macro_rows.append(row_concat) # 所有行纵向拼接(axis=0为垂直方向) macro_combined = np.concatenate(macro_rows, axis=0) # 修正原路径拼写错误并保存图像 Image.fromarray(macro_combined).save('./data/outputs/png/zero-macrofigure.png') matplotlib.pyplot.close('all') # 关闭所有绘图窗口,避免内存泄漏
关键修改点
- 用
cols = 3统一管理每行图像数量,后续调整只需修改此参数 - 用
(num_figures + cols - 1) // cols简化总行数的向上取整计算,替代繁琐的奇偶判断 - 行内拼接改为
axis=1(水平方向),实现每行3张的横向排列 - 增加最后一行补空白图像的逻辑,避免因每行宽度不一致导致拼接失败
- 修正原代码中路径的拼写错误(
outpouts→outputs) - 关闭所有绘图窗口,避免长期运行的内存泄漏问题
内容的提问来源于stack exchange,提问作者user2447290
相关产品推荐
相关产品推荐

