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

如何去除Matplotlib中A4尺寸子图的多余空白边距?

去除Matplotlib A4图中子图的多余空白间隙

问题

我希望在A4尺寸的图形中放置多个子图,但使用以下代码生成的图形存在多余的空白间隙(见附图),请问如何去除这些空白?

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

gs1 = gridspec.GridSpec(8, 2)
gs1.update(wspace=0.025, hspace=0.05) # set the spacing between axes.

plt.figure(figsize=(11.69,8.27)) # for landscape

colors=['c','m','y','k','b','g','r','w']
for i in range(16):
    ax = plt.subplot(gs1[i])
    ax.set_xticklabels([])
    ax.set_yticklabels([])
    ax.tick_params(left = False, bottom = False)
    ax.set_facecolor(colors[i%8])
plt.savefig("toto.png")

子图存在多余空白的效果图

解决方法

1. 调整保存图片参数

最直接的方式是在plt.savefig()中添加bbox_inches='tight'和pad_inches=0,自动裁剪图形边缘的空白:

plt.savefig("toto.png", bbox_inches='tight', pad_inches=0)

2. 启用紧凑布局优化

改用subplots创建子图网格并开启tight_layout=True,让Matplotlib自动优化子图间距:

import matplotlib.pyplot as plt

# 创建8行2列子图网格,启用紧凑布局
fig, axes = plt.subplots(8, 2, figsize=(11.69,8.27), tight_layout=True)
colors=['c','m','y','k','b','g','r','w']

for idx, ax in enumerate(axes.flat):
    ax.set_xticklabels([])
    ax.set_yticklabels([])
    ax.tick_params(left=False, bottom=False)
    ax.set_facecolor(colors[idx%8])
    # 可选:隐藏子图边框消除视觉间隙
    ax.spines[['top', 'right', 'bottom', 'left']].set_visible(False)

plt.savefig("toto.png", bbox_inches='tight', pad_inches=0)

3. 微调GridSpec参数

如果坚持使用gridspec,可以将子图间的间距设为0,配合保存参数使用:

gs1 = gridspec.GridSpec(8, 2)
gs1.update(wspace=0, hspace=0) # 取消子图间的间距

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 05:05:22