Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve autoscale when clearing axes in matplotlib

I want to make a series of plots (meant for creating an animation) and thus I want to reuse the axes and preserve the x and y limits across all plots, so I set ax.autoscale(False). However, when I clear the axes using plt.cla() to draw the next image, the autoscale setting is overridden so I have to set ax.autoscale(False) and the x and y limits on every iteration.

In [49]: fig = plt.figure(1)

In [50]: ax = fig.add_subplot(1, 1, 1)

In [59]: ax.get_autoscale_on()
Out[59]: True

In [60]: ax.autoscale(False)

In [61]: ax.get_autoscale_on()
Out[61]: False

In [62]: plt.cla()

In [63]: ax.get_autoscale_on()
Out[63]: True

so I end up doing ax.lines = [] or ax.lines.pop(), but this forces me to set the color on each plot to avoid the color cycling. If I set hold to False, then the autoscale setting is reset every time I call ax.plot(). Is there any other way to preserve the axes properties while removing all plots?

like image 222
astrojuanlu Avatar asked May 27 '12 09:05

astrojuanlu


1 Answers

Don't call plt.cla(), it will clear current axes. If you want to create animation, use matplotlib.pyplot.draw() instead which will redraw the current figure and I think it's what you want.

from pylab import *
import matplotlib.pyplot as plt
ion()
ax=plt.subplot(111)

line1, = ax.plot(x,y,label='x')

for i in xrange(20):
 #update your data to new x,y
 line1.set_xdata(x)
 line1.set_ydata(y)
 draw()

The CookBook of Matplotlib has some good examples on animations, you may want to check it out.

like image 116
Mayli Avatar answered Sep 23 '22 10:09

Mayli