matplotlib 假设两个子子区共享y轴

de90aj5v  于 2023-03-19  发布在  其他
关注(0)|答案(2)|浏览(180)

这是我的代码,用来在一个子图和一个结果图中创建两个子图。我想让左图和右图共享它们的y轴。

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

outer = fig.add_gridspec(1,2)
axout = outer.subplots()
for i in range (2):
    axout[i].set_xticklabels([])
    axout[i].set_yticklabels([])
    axout[i].axis('off')

inner = outer[0,0].subgridspec(2,1,hspace=0)

ax = inner.subplots(sharex=True)

ax[0].errorbar(hmf_DMO_FIDUCIAL[0],hmf_DMO_FIDUCIAL[1])
ax[0].errorbar(hmf_DMO_FIDUCIAL[0],hmf_DMO_FIDUCIAL[1])
ax[0].errorbar(hmf_DMO_FIDUCIAL[0],STRONGEST_SN_DMO)
ax[0].set_yscale("log")
ax[0].set_xscale("log")

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

inner = outer[0,1].subgridspec(2,1,hspace=0)
ax = inner.subplots(sharex=True)

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

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

fig.tight_layout()
fig.show()

我试过axout = outer.subplots(sharey=True),但这不起作用。

yr9zkbsy

yr9zkbsy1#

您可以使用GridSpecFromSubplotSpec和一些巧妙的“隐藏”轴刻度来实现这一点:

import matplotlib.pyplot as plt 
import matplotlib.gridspec as gridspec

fig = plt.figure()
outer = gridspec.GridSpec(1, 2, wspace=0, hspace=0.2)

inner = gridspec.GridSpecFromSubplotSpec(2, 1,
                subplot_spec=outer[0], wspace=0.1, hspace=0)

ax = plt.Subplot(fig, inner[0])
ax.plot(x, y1)
fig.add_subplot(ax)

ax = plt.Subplot(fig, inner[1])
ax.plot(x, y2)
fig.add_subplot(ax)
    
inner = gridspec.GridSpecFromSubplotSpec(2, 1,
                subplot_spec=outer[1], wspace=0.1, hspace=0)

ax = plt.Subplot(fig, inner[0])
ax.plot(x, y3)
ax.set(yticks=[])
fig.add_subplot(ax)

ax = plt.Subplot(fig, inner[1])
ax.plot(x, y4)
ax.set(yticks=[])
fig.add_subplot(ax)

可以用数据和打印样式替换ax.plot(x, y)

hmmo2u0o

hmmo2u0o2#

这不会与您的代码相同,但显示如何,我已测试植入具有相同y轴:导入matplotlib.pyplot作为plt

# create two subplots with shared x-axis
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)

# plot data on each subplot
ax1.plot([1, 2, 3], [4, 5, 6])
ax2.plot([1, 2, 3], [2, 4, 6])

# set titles for subplots and overall figure
ax1.set(title='Subplot 1')
ax2.set(title='Subplot 2')
fig.suptitle('Two Subplots with Shared X-Axis')

# display the plot
plt.show()

相关问题