0

I have data over large span of x. Now I want the ylim will be automatic for a specified xlim. Just like 'autoscale' in gnuplot or PlotRange->'Automatic' in mathematica.

deltasata
  • 377
  • 1
  • 4
  • 21
  • possible duplicate of [Automatically Rescale ylim and xlim in Matplotlib](http://stackoverflow.com/questions/10984085/automatically-rescale-ylim-and-xlim-in-matplotlib) – sebix Nov 30 '14 at 09:20

1 Answers1

1

Use the min and max values for that range:

>>> data = np.random.random((1000,))
>>> data.shape
(1000,)
>>> plt.plot(data)
[<matplotlib.lines.Line2D object at 0x37b7f50>]
>>> plt.ion()
>>> plt.show()
>>> plt.xlim(450,470)
>>> plt.ylim(np.min(data[450:470+1]), np.max(data[450:470+1]))

Or to use a function doing both:

def plot_autolimit(x, y=None, limit=None):
    if y is None:
        plt.plot(x)
    else:
        plt.plot(x, y)
    if limit is not None:
        plt.xlim(limit)
        if y is None:
            plt.ylim(np.min(x[limit[0]:limit[1]+1]), np.max(x[limit[0]:limit[1]+1]))
        else:
            plt.ylim(np.min(y[limit[0]:limit[1]+1]), np.max(y[limit[0]:limit[1]+1]))

This also works for given x values and all limits you want:

plot_autolimit(np.arange(data.size), data, limit=[3,49])
sebix
  • 2,943
  • 2
  • 28
  • 43
  • Why not use `plt.relim`and `plt.autoscale_view`as suggested in the answer that you linked in the comments of the question? (--> http://stackoverflow.com/questions/10984085/automatically-rescale-ylim-and-xlim-in-matplotlib) – hitzg Nov 30 '14 at 22:29
  • Because I don't copy the solution from there. And it's a duplicate. – sebix Nov 30 '14 at 22:57