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

Matplotlib中如何为绘图添加周边空白区域

为Matplotlib单图添加周边空白的方法

你当前代码里的bbox_inches='tight'会自动裁剪掉绘图周围的空白,这是导致margins和tight_layout(pad=X)无效的核心原因,先移除这个参数再尝试以下方法:

方法1:用subplots_adjust手动控制边距

虽然没使用子图,但plt.subplots_adjust()可以直接调整绘图区域在figure内的占比,通过left/right/top/bottom四个参数设置四周空白的比例(取值0-1,基于figure整体尺寸):

fig = plt.figure(figsize=(14,10))
plt.plot(n, y)
# 示例:左右各留10%空白,上下各留15%空白
plt.subplots_adjust(left=0.1, right=0.9, bottom=0.15, top=0.85)
plt.savefig('figure.png', dpi=200)

方法2:保存时用pad_inches添加空白

如果不想修改绘图阶段的设置,可在保存图片时通过pad_inches参数直接指定要添加的空白尺寸(单位为英寸),注意要将bbox_inches设为None:

fig = plt.figure(figsize=(14,10))
plt.plot(n, y)
# 示例:给四周添加1英寸的空白
plt.savefig('figure.png', bbox_inches=None, pad_inches=1.0, dpi=200)

方法3:修改全局rc参数统一设置边距

如果需要给所有绘图统一设置空白,可修改Matplotlib的全局配置参数:

import matplotlib.pyplot as plt
# 全局设置绘图区域的边距比例
plt.rcParams['figure.subplot.left'] = 0.1
plt.rcParams['figure.subplot.right'] = 0.9
plt.rcParams['figure.subplot.bottom'] = 0.15
plt.rcParams['figure.subplot.top'] = 0.85

fig = plt.figure(figsize=(14,10))
plt.plot(n, y)
plt.savefig('figure.png', dpi=200)

若之后需要恢复默认配置,执行plt.rcParams.update(plt.rcParamsDefault)即可。

内容的提问来源于stack exchange,提问作者Caesar.tcl

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 00:32:36