Search code examples
matplotliblimitaxis

How would ylim be automatic from data for a given xlim in matplotlib?


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.


Solution

  • 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])