使用 matplotlib 对齐两个 y 轴刻度的问题 [英] Trouble with aligning two y-axis ticks with matplotlib

查看:84
本文介绍了使用 matplotlib 对齐两个 y 轴刻度的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用python和matplotlib对齐两组单独的y轴,并且遇到了我不了解的行为.到目前为止,这是我的代码:

 将matplotlib.pyplot导入为mplot将numpy导入为npfig = 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()

这会产生预期的结果(来自 ):>

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

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

谢谢!

解决方案

两个y轴没有相同的限制:在一种情况下,您在自动范围计算中降低了相同的下限值,而在另一种情况下,您没有自动调整范围.如果您用另一个定义了一个yaxis范围,我想您就实现了您想要的:

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

(如果您没有明确设置 ax2 yticks,那么如果您在交互模式下移动超出原始范围,仍然会呈现刻度).

I am attempting to align two sets of separate y-axis using python and matplotlib, and am running into behavior I don't understand. Here is my code so far:

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()

This produces the expected result (from http://postimg.org/image/qowrjnnr5/):

however, changing the definition of t to

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

produces the result (http://postimg.org/image/swanojt0b):

where you can see that the y axis ticks on the right side are off-shifted.

What am I missing in order to prevent this issue?

Thanks!

解决方案

The two y axes do not have the same limits: in one case you fluke the same lower value in the automatic range calculation while in the other you don't. If you define one yaxis range in terms of the other, I think you achieve what you want:

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

(and if you don't explicitly set the ax2 yticks then ticks will still get rendered if you move beyond the original range in interactive mode).

这篇关于使用 matplotlib 对齐两个 y 轴刻度的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆