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

调用matplotlib的savefig(bbox_inches='tight')后如何获取图像尺寸?

获取Matplotlib savefig(bbox_inches='tight')后的图像尺寸

直接用fig.get_size_inches()只能拿到原始画布的尺寸,无法反映bbox_inches='tight'调整后包含所有元素(轴外文本、图例等)的实际图像尺寸。可以通过以下方式在不读取磁盘的情况下计算出最终尺寸:

核心思路

Matplotlib在处理bbox_inches='tight'时,会先计算出包含所有可见元素的边界框(tight bbox),再基于这个边界框确定保存的图像范围。我们可以提前手动计算这个边界框,再结合画布的DPI转换为实际尺寸。

代码实现

import matplotlib.pyplot as plt

# 创建示例图表(包含轴外文本和图例)
fig, ax = plt.subplots()
ax.plot([1, 2, 3])
ax.set_xlabel('X轴垂直文本', rotation=90)
ax.legend(['示例图例'], bbox_to_anchor=(1.05, 1), loc='upper left')

# 获取tight边界框(需要传入渲染器)
renderer = fig.canvas.get_renderer()
tight_bbox = fig.get_tightbbox(renderer)

# 转换为英寸单位的尺寸(DPI表示每英寸的像素点数)
img_width = (tight_bbox.x1 - tight_bbox.x0) / fig.dpi
img_height = (tight_bbox.y1 - tight_bbox.y0) / fig.dpi

print(f"最终图像尺寸(英寸):宽{img_width:.2f}, 高{img_height:.2f}")

# 保存图像(参数保持一致)
plt.savefig('output.png', bbox_inches='tight', dpi=fig.dpi)
plt.close()

说明

  • fig.get_tightbbox(renderer):计算出包含所有元素(包括轴外文本、图例)的最小边界框,返回的坐标单位是与DPI对应的点数。
  • 除以fig.dpi:将点数转换为英寸,得到的尺寸和savefig生成的图像实际尺寸完全一致。
  • 无需额外依赖:整个过程仅使用Matplotlib自身API,不需要PIL/OpenCV等库,也不会产生磁盘IO操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 18:33:25