Python 将两个y轴记号与matplotlib对齐时出现问题

Python 将两个y轴记号与matplotlib对齐时出现问题,python,matplotlib,Python,Matplotlib,我试图使用python和matplotlib对齐两组独立的y轴,但遇到了我不理解的行为。以下是我目前的代码: import matplotlib.pyplot as mplot import numpy as np fig = mplot.figure() ax1 = fig.add_subplot(111) t = np.arange(1, 4, 1) s1 = np.exp(t) ax2 = ax1.twinx() ax1.semilogx(t, s1) ax2.set_yt

我试图使用python和matplotlib对齐两组独立的y轴,但遇到了我不理解的行为。以下是我目前的代码:

import matplotlib.pyplot as mplot 
import numpy as np

fig = mplot.figure()
ax1 = fig.add_subplot(111)

t = np.arange(1, 4, 1)
s1 = np.exp(t)

ax2 = ax1.twinx()    
ax1.semilogx(t, s1)
ax2.set_yticks(2*ax1.get_yticks())
mplot.show()
这将产生预期结果(来自):

但是,将t的定义更改为

t = np.arrange(1, 3, 1)
生成结果():

您可以看到右侧的y轴标记已偏移

为了防止这个问题,我遗漏了什么


谢谢

两个y轴没有相同的限制:在一种情况下,您在自动范围计算中侥幸获得相同的下限值,而在另一种情况下,您没有。如果您将一个yaxis范围定义为另一个,我认为您实现了您想要的:

lim1 = ax1.get_ylim()
lim2 = (lim1[0]*2, lim1[1] *2)
ax2.set_ylim(lim2)
(如果未显式设置ax2 yticks,则如果在交互模式下移动到原始范围之外,则仍将渲染记号)