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

为何Matplotlib savefig保存尺寸与figsize设置不匹配?

如何用Matplotlib生成精确尺寸且无空白的出版物图表

问题描述

我需要制作一张用于出版物的精确尺寸图表,执行以下代码:

fig,axn = plt.subplots(2,2, figsize=(8,8))

x = [2,4,6,8]
y = [10,3,20,4]

sns.scatterplot(x=x, y=y, ax=axn[0,0])

plt.savefig(r"filepath\test.png")

保存得到的PNG文件尺寸为5英寸×5英寸,且边缘带有大量空白。

添加bbox_inches="tight"参数后:

fig,axn = plt.subplots(2,2, figsize=(8,8))

x = [2,4,6,8]
y = [10,3,20,4]

sns.scatterplot(x=x, y=y, ax=axn[0,0])

plt.savefig(r"filepath\test.png",
            bbox_inches="tight"
           )

图片无空白,但尺寸变为6.7英寸×6.4英寸。查资料说bbox_inches='tight'能去空白且保留figsize尺寸,但实际无效。请问是否需要调整figsize来得到正确的绝对尺寸?

解决方案

没错,你得调整figsize来抵消bbox_inches="tight"的裁剪影响,或者换用更精准的布局控制方法,以下是几种可行方案:

1. 反向计算调整初始figsize

bbox_inches="tight"会自动裁掉图表周围的空白,最终尺寸是原figsize减去被裁剪的部分。你可以先通过测试得到裁剪比例,再反向计算初始figsize:
比如你要最终8×8英寸的无空白图表,当前8×8初始尺寸得到6.7×6.4,按比例放大初始尺寸:

  • 宽度:8 / 6.7 ≈ 1.194,初始宽度设为8 * 1.194 ≈ 9.55
  • 高度:8 / 6.4 = 1.25,初始高度设为8 * 1.25 = 10
    调整后代码示例:
fig,axn = plt.subplots(2,2, figsize=(9.55,10))

x = [2,4,6,8]
y = [10,3,20,4]

sns.scatterplot(x=x, y=y, ax=axn[0,0])

plt.savefig(r"filepath\test.png", bbox_inches="tight")

保存后验证尺寸,再根据实际结果微调比例即可。

2. 手动控制边距与子图间距

放弃bbox_inches="tight",直接手动调整布局参数,让内容填满设定的figsize:

  • 用plt.subplots_adjust()设置left、right、top、bottom参数,把边距设为极小值
  • 调整wspace和hspace控制子图间的间距
    示例代码:
fig,axn = plt.subplots(2,2, figsize=(8,8))

x = [2,4,6,8]
y = [10,3,20,4]

sns.scatterplot(x=x, y=y, ax=axn[0,0])

# 手动调整边距和子图间距,根据图表内容微调数值
plt.subplots_adjust(left=0.05, right=0.95, top=0.95, bottom=0.05, wspace=0.2, hspace=0.2)
plt.savefig(r"filepath\test.png")

这种方式能严格保留figsize的尺寸,同时消除多余空白,适合精度要求极高的场景。

3. 用tight_layout()替代bbox_inches="tight"

tight_layout()会自动调整子图位置和间距,适配画布且不改变最终保存尺寸:

fig,axn = plt.subplots(2,2, figsize=(8,8))

x = [2,4,6,8]
y = [10,3,20,4]

sns.scatterplot(x=x, y=y, ax=axn[0,0])

fig.tight_layout()
plt.savefig(r"filepath\test.png")

如果还有少量空白,可搭配pad参数:fig.tight_layout(pad=0),既能保证尺寸不变,又能最大化利用画布空间。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 03:13:17