Matplotlib消除子图间垂直间距问题求助
解决Matplotlib子图垂直间距无法消除的问题
你遇到fig.subplots_adjust(hspace=0)无效的核心原因是:代码创建子图时使用了layout='compressed'参数,该参数会启用Matplotlib自动布局系统,自动调整子图间距以适配内容,直接覆盖了subplots_adjust的手动设置。
可行解决方案
移除自动布局参数,手动控制间距
删除plt.subplots中的layout='compressed',添加fig.subplots_adjust(hspace=0)强制消除垂直间距。关键代码修改
将原代码中的:fig, ax = plt.subplots(6, 1, figsize=(15,20), layout='compressed')替换为:
fig, ax = plt.subplots(6, 1, figsize=(15,20)) fig.subplots_adjust(hspace=0) # 消除子图间垂直间距
额外注意事项
- 你已通过
ax[0].set_xticks([])和ax[0].tick_params(bottom=False)隐藏上方子图的底部刻度,这一步是必要的,避免子图重叠后刻度互相干扰。 - 颜色条的
pad=col_posit设置为-0.1,可能导致颜色条与子图重叠,若不需要该效果,可调整该值(比如设为0.02)。
修改后的核心代码片段
# 移除自动布局参数,手动设置子图间距 fig, ax = plt.subplots(6, 1, figsize=(15,20)) fig.subplots_adjust(hspace=0) col_posit = -0.1 flare_time = dt.datetime.fromtimestamp(event_start_time.timestamp() + 3600) flare_time = mdates.date2num(flare_time) # 后续代码保持不变...
内容的提问来源于stack exchange,提问作者Francesco Azzollini
相关产品推荐
相关产品推荐

