gpt4 book ai didi

python - 使用 matplotlib 对齐两个 y 轴刻度时出现问题

转载 作者:行者123 更新时间:2023-12-01 05:23:08 25 4
gpt4 key购买 nike

我正在尝试使用 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()

这会产生预期的结果(来自 http://postimg.org/image/qowrjnnr5/ ): good result

但是,将 t 的定义更改为

t = np.arrange(1, 3, 1)

产生结果( http://postimg.org/image/swanojt0b ):

bad result

您可以看到右侧的 y 轴刻度已偏移。

为了防止出现此问题,我缺少什么?

谢谢!

最佳答案

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

lim1 = ax1.get_ylim()
lim2 = (lim1[0]*2, lim1[1] *2)
ax2.set_ylim(lim2)

(如果您没有明确设置 ax2 yticks,那么当您在交互模式下超出原始范围时,刻度仍然会被渲染)。

y tick positions corresponding on each side

关于python - 使用 matplotlib 对齐两个 y 轴刻度时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21944139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com