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

如何移除Matplotlib绘图中坐标轴之间的间隙?

解决Matplotlib中坐标轴与绘图内容的间隙问题

你想要移除的是坐标轴和直方图柱子之间的空白间隙对吧?针对你的代码,有几种简单的方法可以实现:

方法1:使用margins()方法直接消除间隙

margins()可以设置坐标轴内容与轴边缘的空白比例,设置为0就能让内容紧贴坐标轴:

修改你的代码,在绘制直方图后添加这两行:

# 给主图设置无间隙
axes1.margins(x=0, y=0)
# 给子图设置无间隙
axes2.margins(x=0, y=0)

方法2:手动调整坐标轴范围贴合数据

如果你想更精确控制范围,可以先获取直方图的统计结果,然后设置坐标轴范围完全匹配数据的最小和最大值:

# 主图处理
n, bins, patches = axes1.hist(sample.Distance, 100)
axes1.set_xlim(bins[0], bins[-1])
axes1.set_ylim(0, max(n))

# 子图处理
n2, bins2, patches2 = axes2.hist(sample2.Distance, 50)
axes2.set_xlim(bins2[0], bins2[-1])
axes2.set_ylim(0, max(n2))

方法3:使用tight_layout()优化整体布局

如果还存在子图之间的布局间隙,可以在af.show()前添加:

af.tight_layout()

这个方法会自动调整子图间距,让整体布局更紧凑。

修改后的完整代码示例

import matplotlib.pyplot as plt

af = plt.figure() # Create diagram
axes1 = af.add_axes([0.15, 0.1, 0.8, 0.8]) # Main Graph
axes2 = af.add_axes([0.4, 0.5, 0.55, 0.4]) # Small Graph

# Big diagram
n, bins, patches = axes1.hist(sample.Distance, 100)
axes1.set_xlabel('km')
axes1.set_ylabel('Number of Observations')
axes1.set_title('Distance: full dataset and sample')
axes1.margins(x=0, y=0) # 消除主图坐标轴间隙

# Small diagram
n2, bins2, patches2 = axes2.hist(sample2.Distance, 50)
axes2.set_xlabel('km')
axes2.margins(x=0, y=0) # 消除子图坐标轴间隙

af.tight_layout() # 优化整体布局
af.show()

需要注意的是,如果你的直方图柱子本身有宽度,margins(0)会让第一个柱子的左边缘对齐x轴起点,最后一个柱子的右边缘对齐x轴终点,完全消除间隙。如果需要保留一点呼吸空间,可以把x=0改成x=0.01这样的小数值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:39:32