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 after I manually set ylim:
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With