【问题标题】:Second matplotlib x-axis related to the first one : wrong tick position第二个matplotlib x轴与第一个相关:错误的刻度位置
【发布时间】:2016-08-18 02:47:00
【问题描述】:

我想在 matplotlib 图中添加第二个 x 轴,而不是添加第二个图,而是添加链接到第一个轴的标签。这个question 中的答案不知何故未能解决第二个轴范围内的问题:

以下代码将第一个 x 轴的 log10 绘制为第二个轴:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure(3,figsize = [5,4])
ax1 = fig.add_subplot(111)
ax1.set_xlabel('first axis')
ax1.set_xlim([0, 120])
ax1.grid(True)

ax2 = ax1.twiny()
ax2.set_xlim(ax1.get_xlim())
# or alternatively :
# ax2.set_xbound(ax1.get_xbound())
second_ticks = np.array([1.,10.,100.])
ax2.set_xticks(second_ticks)
ax2.set_xticklabels(np.log10(second_ticks))
ax2.set_xlabel('second axis')

plt.show()

有效! 现在让我们将ax1.set_xlim([0, 120]) 更改为ax1.set_xlim([20, 120])

现在它失败了。我试过ax2.set_xbound(ax1.get_xbound()),没有任何区别。不知何故,ax2.set_xticks 未能根据正确的 x 限制放置刻度。

编辑:

我试图将ax1.set_xlim([20, 120]) 放在ax2.set_xlim(ax1.get_xlim()) 之后的任何位置,它再次给出了错误的信息:

实际上我不明白ax2.set_xticks() 的含义,它设置了显示ticklabels 的位置不是吗?

编辑:

好的,我们明白了:x_lim 定义ax2.set_xlim(ax1.get_xlim()) 必须在tick 和ticklabel 定义之后。

import numpy as np
import matplotlib.pyplot as plt

plt.close('all')

fig = plt.figure(1,figsize = [5,4])
ax1 = fig.add_subplot(111)
ax1.set_xlabel('first axis')
ax1.grid(True)
ax1.set_xlim([10, 120])

ax2 = ax1.twiny()

second_ticks = np.array([1.,10.,100.])
ax2.set_xticks(second_ticks)
ax2.set_xticklabels(np.log10(second_ticks))
ax2.set_xlabel('second axis')
ax2.set_xlim(ax1.get_xlim())

fig.tight_layout()

plt.show()

谢谢!

问候,

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    我相信您会得到意想不到的结果,因为您将第二轴上的 x-ticks 和 x-tick-labels 强制为预定义的东西。无论您在第二个轴上放置什么 x 刻度,它们都将始终标记为:ax2.set_xticklabels(np.log10(second_ticks))。相反,在第二个轴上更新 x-tick-labels 您在第一个轴上更新它们

    import numpy as np
    import matplotlib.pyplot as plt
    
    fig = plt.figure(3,figsize = [5,4])
    ax1 = fig.add_subplot(111)
    ax1.set_xlabel('first axis')
    x = np.linspace(0,100,num=200)
    ax1.set_xlim([0, 120])
    ax1.grid(True)
    
    ax2 = ax1.twiny()
    ax2.set_xlim(ax1.get_xlim())
    # or alternatively :
    # ax2.set_xbound(ax1.get_xbound())
    # second_ticks = np.array([1.,10.,100.])
    # ax2.set_xticks(second_ticks)
    ax2.set_xlabel('second axis')
    
    # Set the xlim on axis 1, then update the x-tick-labels on axis 2
    ax1.set_xlim([20, 100])
    ax2.set_xticklabels(np.log10(ax1.get_xticks()))
    plt.show()
    

    这能解决您的问题吗? (ps.你的代码有好几个错别字……无法运行……)

    【讨论】:

    • 我更正了错别字。不,它不起作用(请参阅问题中的编辑)。我想我对 ax2.set_ticks() 的作用有误解,matplotlip 的帮助很浅。
    • 好的,我知道了。我误读了您的文字,这与您编写的代码不符。 ax2.set_xlim(ax1.get_xlim()) 必须在最后
    猜你喜欢
    • 1970-01-01
    • 2020-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多