Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically set ylim from data shown on the screen after setting xlim

For example, after I set xlim, the ylim is wider than the range of data points shown on the screen. Of course, I can manually pick a range and set it, but I would prefer if it is done automatically.

Or, at least, how can we determine y-range of data points shown on screen?

plot right after I set xlim: plot right after I set xlim

plot after I manually set ylim: plot after I manually set ylim

like image 754
Liang Avatar asked Aug 11 '13 15:08

Liang


2 Answers

This approach will work in case y(x) is non-linear. Given the arrays x and y that you want to plot:

lims = gca().get_xlim()
i = np.where( (x > lims[0]) &  (x < lims[1]) )[0]
gca().set_ylim( y[i].min(), y[i].max() )
show()
like image 85
Saullo G. P. Castro Avatar answered Nov 04 '22 10:11

Saullo G. P. Castro


To determine the y range you can use

ax = plt.subplot(111)
ax.plot(x, y)
y_lims = ax.get_ylim()

which will return a tuple of the current y limits.

It seems however that you will probably need to automate setting the y limits by finding the value of y data at at your x limits. There are many ways to do this, my suggestion would be this:

import matplotlib.pylab as plt
ax = plt.subplot(111)
x = plt.linspace(0, 10, 1000)
y = 0.5 * x
ax.plot(x, y)
x_lims = (2, 4)
ax.set_xlim(x_lims)

# Manually find y minimum at x_lims[0]
y_low = y[find_nearest(x, x_lims[0])]
y_high = y[find_nearest(x, x_lims[1])]
ax.set_ylim(y_low, y_high)

where the function is with credit to unutbu in this post

import numpy as np
def find_nearest(array,value):
    idx = (np.abs(array-value)).argmin()
    return idx

This however will have issues when the data y data is not linear.

like image 33
Greg Avatar answered Nov 04 '22 12:11

Greg