循环中的matplotlib axes.Axes.secondary_xaxis:只有循环中的最后一个数字是正确的

matplotlib axes.Axes.secondary_xaxis in a loop: only the last figure in the loop is correct

下面的代码似乎工作正常。 但是,如果我更改范围的停止值(m 的最大值), 我意识到只有最后一个图的次轴绘制正确。 最后一张之前的所有图的副轴似乎都遵循最后一张图副轴的比例。

import matplotlib.pyplot as plt
from matplotlib.ticker import (MultipleLocator,
                               AutoMinorLocator,
                               FixedLocator)

dataX = [0, 1 , 2 , 3, 4]  #trivial
dataY = dataX

for m in range(1, 3): #try to change the number "3" and compare the results.
    print(m)
    fig, ax = plt.subplots(dpi=300)
    secax = ax.secondary_xaxis('top',
                               functions=(lambda x: x*m*10,
                                          lambda x: x/m/10))
    ax.plot(dataX, dataY, 'k', ls='dashed', marker='o')
    ax.set_title(f'figure {m}')

    ### below is only to compare between figures, i set the same tick location ###
    Xtick_loc = [0, 1, 2, 3, 4]
    sec_Xtick_loc = []
    for xp in Xtick_loc:
        sec_Xtick_loc.append(xp*m*10)
    print(Xtick_loc, sec_Xtick_loc)

    ax.xaxis.set_major_locator(FixedLocator(Xtick_loc))
    secax.xaxis.set_major_locator(FixedLocator(sec_Xtick_loc))

同一个“图1”,循环的终止值不同,对比一下就清楚了。

我弄错了吗?这个问题有什么解决办法吗? 先谢谢了!

如果我使用 secax = ax.twiny() 它对我有用。本质上,您修改原始轴,然后创建一个双顶次轴并更改刻度标签。请参阅以下代码和图表(我没有 post):

import matplotlib.pyplot as plt
from matplotlib.ticker import (MultipleLocator,
                               AutoMinorLocator,
                               FixedLocator)

dataX = [0, 1 , 2 , 3, 4]  #trivial
dataY = dataX

for m in range(1, 4): #try to change the number "3" and compare the results.
    print(m)
    fig, ax = plt.subplots(dpi=300)

    ax.plot(dataX, dataY, 'k', ls='dashed', marker='o')
    ax.set_title(f'figure {m}')

    ### below is only to compare between figures, i set the same tick location ###
    Xtick_loc = [0, 1, 2, 3, 4]
    sec_Xtick_loc = []
    for xp in Xtick_loc:
        sec_Xtick_loc.append(xp*m*10)
    print(Xtick_loc, sec_Xtick_loc)

    ax.xaxis.set_major_locator(FixedLocator(Xtick_loc))

    # Added code below:
    secax = ax.twiny()
    secax.set_xlim(ax.get_xlim())
    secax.xaxis.set_major_locator(FixedLocator(Xtick_loc))
    secax.xaxis.set_ticklabels(sec_Xtick_loc)