I'm plotting data in Python using matplotlib. I am updating the data of the plot based upon some calculations and want the ylim and xlim to be rescaled automatically. Instead what happens is the scale is set based upon the limits of the initial plot. A MWE is
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)) pyplot.draw()
The first plot command generates a plot from [0,1]
and I can see everything just fine. At the end, the y-data array goes from [0,10)
with most of it greater than 1
, but the y-limits of the figure remain [0,1]
.
I know I can manually change the limits using pyplot.ylim(...)
, but I don't know what to change them to. In the for
loop, can I tell pyplot to scale the limits as if it was the first time being plotted?
xlim() and ylim() to Set Limits of Axes in Matplotlib xlim() and matplotlib. pyplot. ylim() can be used to set or get limits for X-axis and Y-axis respectively. If we pass arguments in these methods, they set the limits for respective axes and if we do not pass any arguments, we get a range of the respective axes.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With