Matplotlib y-axis limits not updating after setting x-axis limits?

I am trying to plot a subset of some data, but the y-axis limits are not updating properly after I set the x-axis limits. Is there a way for matplotlib to update the y-axis limits after setting the x-axis limits?

For example, consider the following graph:

import numpy
import pylab
pylab.plot(numpy.arange(100)**2.0)

      

which gives: Plot 1 full range

which works great. However, if I want to view only the portion from x = 0 to x = 10, the y-scaling is confused:

pylab.plot(numpy.arange(100)**2.0)
pylab.xlim(0,10)

      

which provides: Plot 1 subset.

In the former case, the x and y axes are scaled correctly, in the latter case, the y axis is still scaled the same even if no data is displayed. How do I tell matplotlib to scale the Y axis?

The obvious workarounds would be to construct a subset of the data itself, or to restrict you to reset the y-axis boundaries manually by validating the data, but these are rather cumbersome.

Update:

The above example is simplified, more generally:

pylab.plot(xdata, ydata1)
pylab.plot(xdata, ydata2)
pylab.plot(xdata, ydata3)
pylab.xlim(xmin, xmax)

      

Of course, manual adjustment of the y-axis range is possible.

subidx = N.argwhere((xdata >= xmin) & (xdata <= xmax))
ymin = N.min(ydata1[subidx], ydata2[subidx], ydata3[subidx])
ymax = N.max(ydata1[subidx], ydata2[subidx], ydata3[subidx])
pylab.xlim(xmin, xmax)

      

but that is cumbersome to say the least (imho). Is there a faster way to do this without manually calculating the graphs? Thank!

Update 2:

The autoscale function does some scaling and seems like the right candidate for this job, but handles the axes independently and only scales to the full range of data, no matter what the axis limits are.

+3


source to share


1 answer


In what sense do you mean data validation is cumbersome? If in terms of writing code, then it's not so bad. Try something like

pylab.ylim(numpy.min(data), numpy.max(data))

      

... where it data

could be numpy.arange(100)[0:11]

.



In general, if you have xdata

and ydata

(but if they are sorted), you would need something like

from bisect import bisect
sub_ydata = ydata[bisect(xdata, xmin):bisect(xdata, xmax)]
pylab.ylim(numpy.min(sub_ydata), numpy.max(sub_ydata))

      

If you mean it's hard to compute, then I really can't see how I matplotlib

could do it without computation like that.

+1


source







All Articles