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

如何调整Matplotlib散点图Y轴零点左侧的内边距?

解决Matplotlib散点图Y轴零点左侧添加空白的问题

方法1:手动调整Y轴范围

如果你的Y轴数据最小值接近0,直接手动设置Y轴下限为负数,就能在零点左侧留出空白。示例代码:

import matplotlib.pyplot as plt

# 示例散点数据
x = [1, 2, 3, 4, 5]
y = [0.5, 1.2, 0.8, 1.5, 0.3]
plt.scatter(x, y)

# 获取当前Y轴范围,计算新的下限(在原范围基础上减少20%的空间)
current_ylim = plt.gca().get_ylim()
new_bottom = current_ylim[0] - 0.2 * (current_ylim[1] - current_ylim[0])
plt.gca().set_ylim(bottom=new_bottom)

plt.show()

方法2:关闭Y轴的sticky edges并单独设置边距

你之前的use_sticky_edges=False需要针对Y轴单独生效,再配合Y轴边距设置:

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [0.5, 1.2, 0.8, 1.5, 0.3]
plt.scatter(x, y)

ax = plt.gca()
# 关闭Y轴的sticky edges(避免轴范围被数据边界绑定)
ax.yaxis.set_use_sticky_edges(False)
# 单独设置Y轴的上下边距,0.2表示预留20%的空白空间
plt.margins(y=0.2)

plt.show()

方法3:自动缩放后调整Y轴下限

先让Matplotlib自动适配数据范围,再针对零点左侧补空白,适合Y值全为正数的场景:

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [0.5, 1.2, 0.8, 1.5, 0.3]
plt.scatter(x, y)

ax = plt.gca()
# 先让轴自动适配数据
ax.autoscale()
ylim = ax.get_ylim()
# 如果Y轴下限大于等于0,设置新的负下限来预留空白
if ylim[0] >= 0:
    ax.set_ylim(bottom= -0.2 * (ylim[1] - ylim[0]))

plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 15:54:56