【问题标题】:Adding a subplot that doesn't share an x axis when others do添加当其他人共享时不共享 x 轴的子图
【发布时间】:2013-11-20 11:47:38
【问题描述】:

我正在尝试在子图的底部添加一个子图。我遇到的问题是所有第一组子图都希望共享它们的 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 是否是一个有效的选择,即使我没有固定数量的频道?

非常感谢您的帮助

编辑 乔的形象:

【问题讨论】:

    标签: python matplotlib subplot


    【解决方案1】:

    在这种情况下直接使用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()
    

    【讨论】:

    • 当我运行此代码时,比例不会改变以绘制范围,我的共享轴比例保持在 0.06。我可以给你看一张图片,但不知道在哪里张贴
    • @AshleighClayton - 您可以将其添加到您的问题中,也可以将其发布到 imgur(或类似的图像共享网站)并添加链接作为评论。我可能误解了你要做什么。
    • 我完全复制了你的代码只是为了测试它。我将把图像放在我的问题中。感谢您的帮助
    • @AshleighClayton - 你确定你没有交互式放大吗?无论如何,它仍然证明了您的要求。前三个 x 轴是共享的,而最后一个是独立的。但是,我很可能误解了你的问题。 (?)
    • 谢谢@Joe Kington。我现在明白了谢谢!很难,因为我在绘图时必须循环,我的 x 轴是日期!但我想我现在明白了
    猜你喜欢
    • 1970-01-01
    • 2019-05-31
    • 2018-01-04
    • 2021-01-19
    • 2022-11-10
    • 1970-01-01
    • 2016-10-10
    • 1970-01-01
    • 2020-03-06
    相关资源
    最近更新 更多