当其他子图共享x轴时,添加一个不共享x轴的子图。

3
我正在尝试在子图的底部添加一个次要图。问题是第一组子图都想共享它们的x轴,但底部的子图不想共享。

channels是想共享x轴的子图。
那么我该如何添加一个不共享x轴的子图呢? 这是我的代码:
def plot(reader, tdata):
    '''function to plot the channels'''

channels=[]
        for i in reader:
        channels.append(i)

    fig, ax = plt.subplots(len(channels)+1, sharex=False, figsize=(30,16), squeeze=False)
    plot=0
    #where j is the channel name
    for i, j in enumerate(reader): 

        y=reader["%s" % j]
        ylim=np.ceil(np.nanmax(y))
        x=range(len((reader["%s" % j])))
        ax[plot,0].plot(y, lw=1, color='b')
        ax[plot,0].set_title("%s" % j)
        ax[plot,0].set_xlabel('Time / s')
        ax[plot,0].set_ylabel('%s' % units[i])
        ax[plot,0].set_ylim([np.nanmin(y), ylim+(ylim/100)*10])
        plot=plot+1

    ###here is the new subplot that doesn't want to share the x axis###
    ax[plot, 0].plot()
    plt.tight_layout()
    plt.show()

这段代码无法正常工作,因为它们共享最后一个子图的x轴。通道的长度取决于我之前在代码中指定的内容。
即使我没有恒定的通道数,使用add_subplot是否是有效的选项?
非常感谢您的任何帮助。 编辑 Joe的图片: enter image description here
1个回答

3

在这种情况下,直接使用fig.add_subplot最简单。

以下是一个快速示例:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(6, 8))

# Axes that share the x-axis
ax = fig.add_subplot(4, 1, 1)
axes = [ax] + [fig.add_subplot(4, 1, i, sharex=ax) for i in range(2, 4)]

# The bottom independent axes
axes.append(fig.add_subplot(4, 1, 4))

# Let's hide the tick labels for all but the last shared-x axes
for ax in axes[:2]:
    plt.setp(ax.get_xticklabels(), visible=False)

# And plot on  the first subplot just to demonstrate that the axes are shared
axes[0].plot(range(21), color='lightblue', lw=3)

plt.show()

enter image description here


当我运行这段代码时,比例尺没有改变以绘制范围,我的共享轴比例尺保持在0.06。我可以向您展示一张图片,但不确定在哪里发布它。 - Ashleigh Clayton
@AshleighClayton - 你可以将它添加到你的问题中,或者只需将其发布到imgur(或类似的图像共享网站)并在评论中添加链接。我可能误解了你想做什么。 - Joe Kington
我完全复制了你的代码来测试。我会把图片放在我的问题中。谢谢你的帮助。 - Ashleigh Clayton
@AshleighClayton - 你确定你没有交互放大吗?无论如何,它仍然展示了你所问的内容。前三个x轴是共享的,而最后一个是独立的。但是,我很可能误解了你的问题。(?) - Joe Kington
谢谢@Joe Kington。现在我明白了,谢谢!因为我在绘图时必须循环,并且我的x轴是日期,所以一开始有些困难。但我现在想我弄明白了。 - Ashleigh Clayton

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接