【问题标题】:matplotlib secondary axes that spans half of the first onematplotlib 次轴,跨越第一个轴的一半
【发布时间】:2011-11-15 16:34:08
【问题描述】:

我需要一个有两个 y 轴的图,但第二个应该是第一个的一半。

我在想两个不同的情节重叠,但我想有一个更简单的方法。

非常感谢。

【问题讨论】:

    标签: matplotlib axes


    【解决方案1】:

    您应该查看 matplotlib 库。
    也许您正在寻找类似thisthis 的东西。

    那么如果你想让 ax2(右轴)跨越 ax1(左轴)的一半,得到 ax1 的 y-limits:

    (min_y, max_y) = ax1.get_ylim()
    

    并相应地设置 ax2 限制。例如:

    ax2.set_ylim((min_y, max_y / 2.))
    

    编辑:

    在您的 cmets 之后,我找到了一个可能更符合您需求的解决方案。下面是从 mpl 库修改的代码:

    import numpy as np
    import matplotlib.pyplot as plt
    
    fig = plt.figure()
    ax1 = fig.add_subplot(111)
    t = np.arange(0.01, 10.0, 0.01)
    s1 = np.exp(t)
    ax1.plot(t, s1, 'b-')
    ax1.set_xlabel('time (s)')
    ax1.set_ylabel('exp', color='b')
    
    for tl in ax1.get_yticklabels():
        tl.set_color('b')
    
    ax2 = ax1.twinx()
    s2 = np.sin(2*np.pi*t)
    ax2.plot(t, s2, 'r.')
    ax2.set_ylabel('sin', color='r')
    
    (min_y, max_y) = ax2.get_ylim()
    dist = (max_y - min_y) * 2.
    
    ax2.set_ylim((min_y, max_y + dist))
    
    yticklabels = ax2.get_yticklabels()
    yticks = ax2.get_yticklines()
    
    nlabels = len(yticklabels) / 2
    nticks = len(yticks) / 2
    
    for i in range(len(yticklabels)):
        if i < nlabels:
            yticklabels[i].set_color('r')
        else:
            yticklabels[i].set_visible(False)
    
    for i in range(len(yticks)):
        if i < nticks:
            yticks[i].set_color('r')
        else:
            yticks[i].set_visible(False)
    
    plt.show()
    

    【讨论】:

    • 这正是我所需要的!太感谢了。其实并没有我想的那么容易……
    猜你喜欢
    • 2014-09-04
    • 1970-01-01
    • 2017-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-25
    相关资源
    最近更新 更多