allenfrostline

Animation in Matplotlib?


2019-04-25

In this tiny piece of post I’m gonna post how you can make animations using the matplotlib module in Python. Things get much more intuitive when they move, don’t they?

We’re here trying to plot two (thick) sine curves which have different offsets on the x-axis direction, and those offsets increases with an indicator called frame_no.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation


plt.rcParams['animation.html'] = 'html5'

x = np.linspace(0, 10, 100)

fig = plt.figure(figsize=(10, 3))
ax = fig.add_subplot(111)
line1 = ax.plot([], [], color='skyblue', lw=100)[0]
line2 = ax.plot([], [], color='deepskyblue', lw=100)[0]
plt.axis('off')

def init():
    ax.set_xlim(0, 10)
    ax.set_ylim(-.5, 20.5)

def animate(frame_no):
    line1.set_data(x, np.sin(2 * (x - frame_no / 100 * 2 * np.pi)))
    line2.set_data(x, np.sin(2 * (x + frame_no / 100 * 2 * np.pi)) + .5)

anim = FuncAnimation(fig, animate, frames=100, interval=10, init_func=init)
plt.show()

The plot is altered bit by bit as frame_no changes with frames. You can also try different fps configurations by changing the interval argument. Also, repetition is set true by default, but you may still forbid it by specifying repeat as false in FuncAnimation. Finally, you would have a plot as follows:

Lovely, isn’t it?