使用y轴自动缩放进行交互式缩放



我正在尝试将交互式缩放的行为更改为矩形,以便根据新的可见x轴范围在y轴上自动缩放数据。事实上,我正在探索大量具有大动态的遥测数据,我需要来回缩放很多。因此,对y轴进行自动缩放是件好事。在谷歌上搜索了很多论坛之后,我没有找到任何有助于实现这一点的东西。或者可能是我找错了。有人能给我一些指导吗?

一个选项是连接到xlim_changed信号,并根据当前x极限计算y轴的新极限,以便包括所有数据。

下面的操作比最初想象的要复杂一些,因为仅仅设置y限制是行不通的,因为它们会被缩放触发的(同时(ylim_changed事件覆盖。因此,有一个计时器设置为10毫秒,在处理完该事件后,它会人为地设置限制。

import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt
class AutoScaleY():
def  __init__(self, line, margin=0.05):
self.margin = margin
self.line = line
self.ax = line.axes
self.ax.callbacks.connect('xlim_changed', self.rescale_y)
def rescale_y(self,evt=None):
xmin, xmax = ax.get_xlim()
x, y = line.get_data()
cond = (x >= xmin) & (x <= xmax)
yrest = y[cond]
margin = (yrest.max()-yrest.min())*self.margin
self.ybounds = [yrest.min()-margin, yrest.max()+margin]
self.timer = self.ax.figure.canvas.new_timer(interval=10)
self.timer.single_shot = True
self.timer.add_callback(self.change_y)
self.timer.start()
def change_y(self):
self.ax.set_ylim(self.ybounds)
self.ax.figure.canvas.draw()

x=np.linspace(0,100,1001)
y = np.sin(x/16) + np.cumsum(np.random.randn(1001))/30.
fig, ax = plt.subplots()
line, = ax.plot(x,y)
r = AutoScaleY(line)
plt.show()

最新更新