In [7]:
%pylab inline


Populating the interactive namespace from numpy and matplotlib

In [8]:
from tempfile import NamedTemporaryFile

VIDEO_TAG = """<video controls>
 <source src="data:video/x-m4v;base64,{0}" type="video/mp4">
 Your browser does not support the video tag.
</video>"""

def anim_to_html(anim):
    if not hasattr(anim, '_encoded_video'):
        with NamedTemporaryFile(suffix='.mp4') as f:
            anim.save(f.name, fps=20, extra_args=['-vcodec', 'libx264'])
            video = open(f.name, "rb").read()
        anim._encoded_video = video.encode("base64")
    
    return VIDEO_TAG.format(anim._encoded_video)

from IPython.display import HTML

def display_animation(anim):
    plt.close(anim._fig)
    return HTML(anim_to_html(anim))

In [9]:
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

# animation function.  This is called sequentially
def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=100, interval=20, blit=True)

# call our new function to display the animation
display_animation(anim)


---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-9-b51bfc0123f6> in <module>()
     23 
     24 # call our new function to display the animation
---> 25 display_animation(anim)

<ipython-input-8-c8da01cb9947> in display_animation(anim)
     19 def display_animation(anim):
     20     plt.close(anim._fig)
---> 21     return HTML(anim_to_html(anim))

<ipython-input-8-c8da01cb9947> in anim_to_html(anim)
      9     if not hasattr(anim, '_encoded_video'):
     10         with NamedTemporaryFile(suffix='.mp4') as f:
---> 11             anim.save(f.name, fps=20, extra_args=['-vcodec', 'libx264'])
     12             video = open(f.name, "rb").read()
     13         anim._encoded_video = video.encode("base64")

/usr/lib/python2.7/dist-packages/matplotlib/animation.pyc in save(self, filename, writer, fps, dpi, codec, bitrate, extra_args, metadata, extra_anim, savefig_kwargs)
    750                     #TODO: Need to see if turning off blit is really necessary
    751                     anim._draw_next_frame(d, blit=False)
--> 752                 writer.grab_frame(**savefig_kwargs)
    753 
    754         # Reconnect signal for first draw if necessary

/usr/lib/python2.7/contextlib.pyc in __exit__(self, type, value, traceback)
     22         if type is None:
     23             try:
---> 24                 self.gen.next()
     25             except StopIteration:
     26                 return

/usr/lib/python2.7/dist-packages/matplotlib/animation.pyc in saving(self, *args)
    175         self.setup(*args)
    176         yield
--> 177         self.finish()
    178 
    179     def _run(self):

/usr/lib/python2.7/dist-packages/matplotlib/animation.pyc in finish(self)
    363             raise RuntimeError('Error creating movie, return code: '
    364                                + str(self._proc.returncode)
--> 365                                + ' Try running with --verbose-debug')
    366 
    367     def cleanup(self):

RuntimeError: Error creating movie, return code: 1 Try running with --verbose-debug

In [10]:
%pylab inline


Populating the interactive namespace from numpy and matplotlib

In [14]:
%matplotlib qt
import numpy as np
from matplotlib import pyplot as plt
plt.style.use('ggplot')
from matplotlib import animation

fig = plt.figure()
fig.set_dpi(100)
fig.set_size_inches(7, 6.5)

ax = plt.axes(xlim=(0, 10), ylim=(0, 10))
patch = plt.Circle((5, -5), 0.75, fc='y')


def init():
    patch.center = (5, 5)
    ax.add_patch(patch)
    return patch,


def animate(i):
    x, y = patch.center
    x = 5 + 3 * np.sin(np.radians(i))
    y = 5 + 3 * np.cos(np.radians(i))
    patch.center = (x, y)
    return patch,

anim = animation.FuncAnimation(fig, animate,
                               init_func=init,
                               frames=360,
                               interval=20,
                               blit=True)