Draw animation graph using Python Matplotlib.pyplot


The result is:

Draw animation graph using Python Matplotlib.pyplot

This page shows an example of the animation generated by the matplotlib.pyplot of python.


In [1]:
import numpy as np
import matplotlib.pyplot as plt

from matplotlib import animation
from IPython.display import HTML
In [2]:
dn = np.random.choice([-1,1], size=100)
swalk = np.cumsum(dn)

# First set up the figure, the axis, and the plot element we want to animate
fig, ax = plt.subplots()

ax.set_xlim(( 0, 100))
ax.set_ylim((-10, 10))

line, = ax.plot([], [], lw=2)
plt.close()

# 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.arange(i)
    y = swalk[:i]
    line.set_data(x, y)
    return (line,)
# equivalent to rcParams['animation.html'] = 'html5'
plt.rcParams['animation.html'] = 'html5'

# 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=50, blit=True)
In [3]:
anim
Out[3]:
In [4]:
anim.save('demoanimation.mp4', writer='ffmpeg',fps=1000/50);
anim.save('demoanimation.gif', writer='imagemagick',fps=1000/50);