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

如何在matplotlib图表中居中显示由spines轴线构成的绘图框?

Matplotlib 绘图区域居中实现方法

有两种常用方案可以解决轴线四周留白不均、让绘图框整体居中的问题:

  • 方案1:使用自动布局参数constrained_layout,matplotlib会自动计算刻度、标签所需空间,调整边距实现居中,无需手动计算参数:
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 1, 32)
# 创建画布时开启自动约束布局
fig, ax = plt.subplots(constrained_layout=True)
ax.plot(x, x**2)
# 保存或展示都可生效
plt.savefig("test.png")
plt.show()
  • 方案2:手动固定四边边距,如果你需要四周留白宽度完全一致,可以通过subplots_adjust手动指定四边留白的比例:
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 1, 32)

plt.plot(x, x**2)
# 左右、上下边距分别对称设置即可保证绘图区居中,数值可根据自己的刻度大小调整
plt.subplots_adjust(left=0.15, right=0.85, bottom=0.15, top=0.85)
plt.savefig("test.png")
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 22:24:04