user3123955
user3123955

Reputation: 2901

Matplotlib scale y axis based on manually zoomed x axis

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.

Is this possible with matplotlib?

Upvotes: 2

Views: 2278

Answers (1)

Falko
Falko

Reputation: 17877

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.

Some comments:

  • I'm using pylab, since it provides useful functions for generating examle data. But you can import the matplotlib library as well.
  • The ondraw event handler gets the current x limits of the current axes gca(), selects y values with corresponding x 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 calls ondraw to update the y limits.

Upvotes: 2

Related Questions