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

如何让Matplotlib嵌套子图中的左右两组子图共享Y轴?

解决嵌套子图跨组共享Y轴的问题

你当前生成的图表中,左右两组上下排布的子图Y轴相互独立,无法同步刻度和范围。你尝试的outer.subplots(sharey=True)无效,是因为该参数作用的是外层的两个轴,但你已经将外层轴隐藏,实际用于绘图的是每个外层格子内的嵌套子图。要实现左右对应子图共享Y轴,需要让左侧的上/下子图分别与右侧的上/下子图建立共享关联。

修改后的代码

import matplotlib.pyplot as plt

fig = plt.figure()
fig.suptitle('L1000N1800 AGN HMFs')

outer = fig.add_gridspec(1,2)
axout = outer.subplots()
for i in range(2):
    axout[i].axis('off')  # 直接隐藏外层轴,无需单独清除刻度标签

# 创建左侧嵌套子图并保存引用
inner_left = outer[0,0].subgridspec(2,1, hspace=0)
ax_left = inner_left.subplots(sharex=True)

# 左侧子图绘图
ax_left[0].errorbar(hmf_DMO_FIDUCIAL[0], hmf_DMO_FIDUCIAL[1])
ax_left[0].errorbar(hmf_DMO_FIDUCIAL[0], hmf_DMO_FIDUCIAL[1])
ax_left[0].errorbar(hmf_DMO_FIDUCIAL[0], STRONGEST_SN_DMO)
ax_left[0].set_yscale("log")
ax_left[0].set_xscale("log")

ax_left[1].errorbar(hmf_DMO_FIDUCIAL[0], hmf_DMO_FIDUCIAL[1])
ax_left[1].set_yscale("log")

# 创建右侧嵌套子图时,指定共享左侧对应子图的Y轴
inner_right = outer[0,1].subgridspec(2,1, hspace=0)
ax_right = inner_right.subplots(sharex=True, sharey=[ax_left[0], ax_left[1]])

# 右侧子图绘图
ax_right[0].errorbar(hmf_DMO_FIDUCIAL[0], hmf_DMO_FIDUCIAL[1])
ax_right[0].errorbar(hmf_DMO_FIDUCIAL[0], hmf_DMO_FIDUCIAL[1])
ax_right[0].set_xscale("log")  # Y轴共享后无需重复设置yscale

ax_right[1].errorbar(hmf_DMO_FIDUCIAL[0], hmf_DMO_FIDUCIAL[1])

# 隐藏右侧子图的Y轴标签,避免重复显示,优化布局
ax_right[0].set_yticklabels([])
ax_right[1].set_yticklabels([])

fig.tight_layout()
fig.show()

关键说明

  • 保存左侧子图的引用ax_left,在创建右侧子图时通过sharey=[ax_left[0], ax_left[1]],让右侧上下子图分别与左侧对应子图共享Y轴
  • Y轴共享后,右侧子图的刻度、范围会自动与左侧保持一致,无需重复设置yscale
  • 隐藏右侧子图的Y轴标签,可避免重复信息,让图表布局更简洁

你也可以在创建完所有子图后,通过手动调用ax_right[0].sharey(ax_left[0])和ax_right[1].sharey(ax_left[1])实现相同的共享效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 05:53:24