Liang
Liang

Reputation: 1075

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

Upvotes: 11

Views: 10322

Answers (4)

bp91
bp91

Reputation: 41

Small improvement of previous answer for case of multiple lines plotted:

def autoset_ylim(ax): # after ax.set_xlim((xstart,xend))
    xlim = ax.get_xlim()
    ymin = None ; 
    ymax = None;
    for line in ax.lines:
        x=line.get_xdata()
        y=line.get_ydata()
        i = np.where( (x > xlim[0]) &  (x < xlim[1]) )[0]
        if ymin == None:
            ymin = y[i].min()
            ymax = y[i].max()
        else:
            ymin = min(ymin,y[i].min())
            ymax = max(ymax,y[i].max())
    ax.set_ylim((ymin,ymax))
    return 

Upvotes: 0

wander95
wander95

Reputation: 1376

I found @Saullo Castro's answer useful and have slightly improved it. Chances are that you want to do adjust limits many different plots.

import numpy as np
def correct_limit(ax, x, y):   
   # ax: axes object handle
   #  x: data for entire x-axes
   #  y: data for entire y-axes
   # assumption: you have already set the x-limit as desired
   lims = ax.get_xlim()
   i = np.where( (x > lims[0]) &  (x < lims[1]) )[0]
   ax.set_ylim( y[i].min(), y[i].max() ) 

Upvotes: 2

Saullo G. P. Castro
Saullo G. P. Castro

Reputation: 59005

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()

Upvotes: 8

Greg
Greg

Reputation: 12234

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.

Upvotes: 2

Related Questions