将第二个 y 轴与左侧的对齐?

Align second y axis with the one on the left?

我引入了双 yaxis 来绘制累积值,但 0 不是从图像底部开始的,或者至少与左侧 yaxis 的高度相同。

如何将右边的0点和左边的y对齐?

fig, ax = plt.subplots(1,1, figsize=(15,1.5*2.5))
ax.hist(np.arange(100), np.arange(100))
axt = ax.twinx()
axt.plot(np.arange(100), np.arange(100), ls=':', c='r')

不幸的是 set_ylim 它改变了刻度分辨率。

您可以使用命令

将两个 y 轴设置为具有相等的限制
axt.set_ylim(ax.get_ylim())

您执行完所有绘图命令后。同样,如果您只希望较低的值(0)重合,您可以

axt.set_ylim([ax.get_ylim()[0],axt.get_ylim()[1]])

这是有效的,因为 ax.get_ylim() returns 一个元组,其中第一个条目是下限,第二个值是显示轴范围的上限。 set_ylim() 反过来需要一个双元素可迭代对象(例如列表或元组),您可以动态构建它。

编辑:

正如 tmdavison in the comments, one can also just pass one of the limits to set_xlim(), thereby leaving the other limit unchanged (see the documentation 所指出的细节)。这是通过关键字 bottomtop 完成的。对于OP中的例子,只设置双轴下限为0的方法,相应的命令是

axt.set_ylim(bottom=ax.get_ylim()[0])