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

Matplotlib绘图尺寸调整及绘图空白去除问题求助

我来帮你搞定这两个Matplotlib的问题,咱们一个个说:

1. 如何调整Matplotlib中的绘图尺寸?

调整绘图尺寸有几种常用的方式,根据你的使用场景选就行:

  • 创建Figure时直接指定尺寸:在初始化plt.figure()的时候,用figsize参数设置宽和高(单位是英寸),比如你代码里的fig = plt.figure(figsize=(7,7))就是创建一个7×7英寸的方形图。如果需要横向图,就设成figsize=(10,6)这种比例。
  • 修改已存在的Figure尺寸:如果已经创建了Figure对象,之后想改尺寸,可以调用fig.set_size_inches(width, height),比如fig.set_size_inches(8, 5)就能把图改成8×5英寸。
  • 用subplots批量创建子图时指定尺寸:如果用plt.subplots()一次性创建多个子图,也可以直接加figsize参数,比如fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(9,7)),这样整个图的尺寸就会按你设置的来。
2. 修复绘图右侧及底部的大片空白问题

看了你的脚本,主要有几个小问题导致了多余空白,咱们一步步改:

首先,你的保存顺序错了!

你先调用了plt.close(fig)再执行fig.savefig(name),这会导致保存的图要么空白要么显示异常——因为关闭Figure之后,Matplotlib就不会再维护这个图的内容了。一定要先保存,再关闭。

其次,子图网格布局太宽松

你用了(4,3)的网格,但只用到了前两行的前两列,剩下的网格空间直接变成了右侧和底部的空白。不如改成(2,2)的网格,刚好匹配你的4个子图,从根源减少空白。

最后,配合布局优化和保存参数裁剪空白

推荐在创建Figure时开启constrained_layout=True,它会比plt.tight_layout()更智能地自动调整子图间距和整体布局;另外在保存时加上bbox_inches='tight'和pad_inches参数,能自动裁剪掉图周围的多余空白,同时保留一点边距避免内容被截断。

修改后的完整脚本示例:

# 创建Figure时开启自动布局,同时设置尺寸
fig = plt.figure(figsize=(7,7), constrained_layout=True)
# 改用(2,2)网格,刚好放下4个子图,避免冗余空间
ax1 = plt.subplot2grid((2,2), (0,0))
ax2 = plt.subplot2grid((2,2), (1,0))
ax3 = plt.subplot2grid((2,2), (0,1))
ax4 = plt.subplot2grid((2,2), (1,1))

data = self.dframe[i]
tes = print_data(data, self.issues, self.color, self.type_user)
tes.print_top(data=data, top=10, ax=ax1, typegraph="hbar", problem=self.issues[i], tone=self.color[i])
tes.print_top(data=data, top=10, ax=ax2, typegraph="prod_bar", problem=self.issues[i], tone=self.color[i])
tes.print_top(data=data, top=10, ax=ax3, typegraph="reg_hbar", problem=self.issues[i], tone=self.color[i])
tes.print_top(data=data, top=10, ax=ax4, typegraph=self.type_user, problem=self.issues[i], tone=self.color[i])

problem = self.issues[i]
name = problem + '.PNG'
# 保存时裁剪空白,保留0.1英寸边距防止内容截断
fig.savefig(name, bbox_inches='tight', pad_inches=0.1)
# 保存完成后再关闭Figure
plt.close(fig)

额外小提示:

如果你的子图坐标轴标签/标题太长,也可能导致局部空白,可以通过旋转标签来优化,比如给某个子图加ax1.tick_params(axis='x', rotation=45),让x轴标签倾斜显示,节省空间。

内容的提问来源于stack exchange,提问作者Rafael Rodrigues Santos

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:08:48