如何在Matplotlib中按图形对象尺寸保存图片?
解决Matplotlib保存图片空白边距的方案
方法1:用bbox_inches='tight'自动裁剪
保存图片时给savefig()加这个参数,能自动裁掉周围空白:
import matplotlib.pyplot as plt # 示例绘图代码 plt.plot([1,2,3], [4,5,6]) plt.savefig('result.png', bbox_inches='tight')
要彻底消除细微空白,搭配pad_inches=0:
plt.savefig('result.png', bbox_inches='tight', pad_inches=0)
方法2:手动调整子图边距
用subplots_adjust()精准控制子图与画布的边距比例:
plt.plot([1,2,3], [4,5,6]) # 把上下左右边距都设为0,让子图填满画布 plt.subplots_adjust(left=0, right=1, top=1, bottom=0) plt.savefig('result.png')
方法3:用tight_layout()优化布局
绘制完成后调用该方法,Matplotlib会自动调整子图间距和整体边距:
plt.plot([1,2,3], [4,5,6]) plt.tight_layout() plt.savefig('result.png')
也可以和bbox_inches='tight'组合使用,进一步优化效果。
方法4:匹配画布与图形尺寸
先定义画布大小,再让子图填满画布:
# 设置画布尺寸(宽8、高6英寸,可按需调整) fig, ax = plt.subplots(figsize=(8,6)) ax.plot([1,2,3], [4,5,6]) # 去掉子图内部的空白边距 ax.margins(0) plt.savefig('result.png', bbox_inches='tight', pad_inches=0)
内容的提问来源于stack exchange,提问作者Miguel
相关产品推荐
相关产品推荐

