Automatically Rescale ylim and xlim in Matplotlib

You will need to update the axes’ dataLim, then subsequently update the axes’ viewLim based on the dataLim. The approrpiate methods are axes.relim() and ax.autoscale_view() method.
Your example then looks like:

import random
import matplotlib.pyplot as pyplot

pyplot.ion()

x = range(10)
y = lambda m: [m*random.random() for i in range(10)]

pLine, = pyplot.plot(x, y(1))

for i in range(10):
    pLine.set_ydata(y(i+1))

ax = pyplot.gca()

# recompute the ax.dataLim
ax.relim()
# update ax.viewLim using the new dataLim
ax.autoscale_view()
pyplot.draw()

Leave a Comment