绘制x和y辅助轴时缺少一个辅助标签

时间:2014-03-06 16:53:53

标签: python matplotlib plot

我来自这个问题Matplotlib: two x axis and two y axis我在那里学习了如何在同一个地块上绘制两个xy轴。

这是MWE

import matplotlib.pyplot as plt
import numpy as np

# Generate random data.    
x1 = np.random.randn(50)
y1 = np.linspace(0, 1, 50)
x2 = np.random.randn(20)+15.
y2 = np.linspace(10, 20, 20)

# Plot both curves.
fig = plt.figure()

ax1 = fig.add_subplot(111)
ax1.set_xlabel('x_1')
ax1.set_ylabel('y_1')
plt.plot(x1, y1, c='r')

ax2 = ax1.twinx().twiny()
ax2.set_xlabel('x_2')
ax2.set_ylabel('y_2')
plt.ylim(min(y2), max(y2))
ax2.plot(x2, y2, c='b')

plt.show()

这是输出:

enter image description here

y轴和顶部x轴对应蓝色曲线。

如您所见,即使定义了第二个y标签,也会丢失。我已经尝试了许多不同的方法,但我无法让它显示出来。我做错了吗?


添加:

显然该行存在问题:

ax2 = ax1.twinx().twiny()

如果我这样颠倒它:

ax2 = ax1.twiny().twinx()

然后它是第二个x标签,不会显示。

1 个答案:

答案 0 :(得分:2)

基本上,正在发生的是创建了第三个轴对象,您当前没有保留对它的引用。 ax2的可见y轴实际上属于第三个轴对象。

你有几个选择。

  1. 保留对“隐藏”轴对象的引用并设置其y标签。
  2. 请勿使用twinxtwiny,而是创建与第一个轴位于同一位置的轴。
  3. 第二个选项是触摸更详细,但其优点是第二个图上的y轴限制将按照您的预期自动缩放。您不需要像现在一样手动设置它们。

    无论如何,这是第一个选项的例子:

    import matplotlib.pyplot as plt
    import numpy as np
    
    # Generate random data.
    x1 = np.random.randn(50)
    y1 = np.linspace(0, 1, 50)
    x2 = np.random.randn(20)+15.
    y2 = np.linspace(10, 20, 20)
    
    # Plot both curves.
    fig, ax1 = plt.subplots()
    
    ax1.set(xlabel='x_1', ylabel='y_1')
    ax1.plot(x1, y1, c='r')
    
    tempax = ax1.twinx()
    ax2 = tempax.twiny()
    ax2.plot(x2, y2, c='b')
    ax2.set(xlabel='x_2', ylim=[min(y2), max(y2)])
    tempax.set_ylabel('y_2', rotation=-90)
    
    plt.show()
    

    ......这是第二个选项的例子:

    import matplotlib.pyplot as plt
    import numpy as np
    
    def twinboth(ax):
        # Alternately, we could do `newax = ax._make_twin_axes(frameon=False)`
        newax = ax.figure.add_subplot(ax.get_subplotspec(), frameon=False)
        newax.xaxis.set(label_position='top')
        newax.yaxis.set(label_position='right', offset_position='right')
        newax.yaxis.get_label().set_rotation(-90) # Optional...
        newax.yaxis.tick_right()
        newax.xaxis.tick_top()
        return newax
    
    # Generate random data.
    x1 = np.random.randn(50)
    y1 = np.linspace(0, 1, 50)
    x2 = np.random.randn(20)+15.
    y2 = np.linspace(10, 20, 20)
    
    # Plot both curves.
    fig, ax1 = plt.subplots()
    
    ax1.set(xlabel='x_1', ylabel='y_1')
    ax1.plot(x1, y1, c='r')
    
    ax2 = twinboth(ax1)
    ax2.set(xlabel='x_2', ylabel='y_2')
    ax2.plot(x2, y2, c='b')
    
    plt.show()
    

    两者产生相同的输出:

    enter image description here