Matplotlib 基于手动缩放的 x 轴缩放 y 轴 [英] Matplotlib scale y axis based on manually zoomed x axis
问题描述
我有很多在 x 轴上相关的数据,但都以非常不同的 Y 值为中心.x 上的数据也很长,因此很难看到细节.我希望能够为数据集手动设置 x 轴,然后让绘图根据位于手动设置的 x 轴内的数据点的值重新调整 y 轴本身.
I have a lot of data that is correlated on the x axis but are all center around very different Y values. The data is also very long on the x so its hard to see details. I want to be able to set the x axis manually for the data set and then have the plot rescale the y axis itself based on the values of the data points that lie inside that manually set x axis.
这可以用 matplotlib 实现吗?
Is this possible with matplotlib?
推荐答案
根据 mdurant 的评论,我写了一些最小的例子作为你的起点:
Based on the comment from mdurant I wrote some minimal example as a starting point for you:
import pylab as pl
pl.figure()
x = pl.rand(30)
x.sort()
y = pl.sin(2 * pl.pi * x) + 0.1 * pl.randn(30)
pl.plot(x, y)
def ondraw(event):
xlim = pl.gca().get_xlim()
y_sel = y[pl.logical_and(x > xlim[0], x < xlim[1])]
pl.gca().set_ylim((y_sel.min(), y_sel.max()))
pl.gcf().canvas.mpl_connect('draw_event', ondraw)
您可能想要添加更多事件来处理鼠标移动等.
You might want to add more events to handle mouse movements etc.
一些评论:
- 我正在使用
pylab
,因为它提供了用于生成示例数据的有用函数.但是您也可以导入matplotlib
库. ondraw
事件处理程序获取当前轴的当前 x 范围gca()
,选择具有相应x 的
x 范围内的坐标,并设置由所选坐标的最小和最大 y 值确定的新 y 限制.y
值- 使用
mpl_connect
,我们将事件处理程序附加到当前轴.每次绘制轴时 - 例如由于新的绘图命令或手动用户交互 - 它调用ondraw
来更新 y 限制.
- I'm using
pylab
, since it provides useful functions for generating examle data. But you can import thematplotlib
library as well. - The
ondraw
event handler gets the current x limits of the current axesgca()
, selectsy
values with correspondingx
coordinates within the x limits and sets new y limits determined by the minimum and maximum y value of selected coordinates. - With
mpl_connect
we attach the event handler to the current axes. Every time the axes is drawn - e.g. due to new plotting commands or manual user interaction - it callsondraw
to update the y limits.
这篇关于Matplotlib 基于手动缩放的 x 轴缩放 y 轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!