1

I'm attempting to animate (at run time) unlike this answer in mac os and ipython notebook 2.0. I have the following code:

%pylab inline
import time, sys
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import clear_output
f, ax = plt.subplots()

x = np.linspace(0,6,200)

for i in range(10):
  y = i/10*np.sin(x) 
  print i
  ax.plot(x,y)
  time.sleep(0.1)
  clear_output(True)
  display(f)
  ax.cla() # turn this off if you'd like to "build up" plots
plt.close()

Which seems to almost work, as the print is working without flashing (a previous problem, corrected by clear_output), but the axes are not updating.

Community
  • 1
  • 1
ChrisE
  • 33
  • 5

1 Answers1

1

The issue here is that i is an integer, so the line y = i/10*np.sin(x) does integer division, which always returns 0. It is animating! But the result is always a flat line at 0. Change that line to

y = float(i)/10*np.sin(x)

When you do that, you'll notice that it doesn't animate in a very nice way. To make it look better, we can explicitly set the y-axis limits instead of letting Matplotlib do it automatically. Inside your loop, add the line

ax.set_ylim(-1, 1)

The final code below animates nicely.

%pylab inline
import time, sys
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import clear_output
f, ax = plt.subplots()

x = np.linspace(0,6,200)

for i in range(10):
  y = float(i)/10*np.sin(x) 
  print i
  ax.set_ylim(-1, 1)
  ax.plot(x,y)
  time.sleep(0.1)
  clear_output(True)
  display(f)
  ax.cla() # turn this off if you'd like to "build up" plots
plt.close()
tbekolay
  • 17,201
  • 3
  • 40
  • 38