Back to the blog

Animated graphics with Python

Animating a mathematical function in matplotlib using FuncAnimation: the wave is redrawn at each frame by shifting the sine argument, as if the wave were traveling to the right.

\[y(x, t) = \sin(x + \omega t)\]
import numpy as np
import matplotlib.animation as animation
import matplotlib.pyplot as plt

# Creating the figure and axis
fig, ax = plt.subplots()

# Values of x
x = np.arange(0, 4*np.pi, 0.01)

"""
The sine function is plotted. By adding a comma after 'line',
the first value in the list is taken and not the list itself
"""
line, = ax.plot(x, np.sin(x))

# Animate function
def animate_sin(i):
    line.set_ydata(np.sin(x + i/10.0))
    return line,

# Running and saving the animation
animation_sin = animation.FuncAnimation(fig, animate_sin, frames = 101, interval = 30, blit = True)
ax.set_xlabel('x')
ax.set_ylabel('y')
plt.title('Animated graph of the sine function')
plt.grid()
animation_sin.save("animated_sine_function.mp4", writer="ffmpeg")
plt.show()

The result — rendered here as GIF:

Animated sine function

Key points in the code:

  • line, (with the comma) performs tuple unpacking — ax.plot() returns a list with a single Line2D object, and we need the direct reference to call set_ydata() on each frame.
  • blit = True speeds up rendering: it redraws only the pixels that change, not the entire figure. It works well as long as the animation function returns the modified artists.
  • frames = 101, interval = 30 produces ~3 seconds of animation at 33 fps.
  • Saving as MP4 requires ffmpeg; saving as GIF requires pillow (included with matplotlib by default). For Jupyter notebooks you can display inline with HTML(ani.to_jshtml()) without writing to a file.

This same structure works for simulating any temporal phenomenon: traveling waves, dynamical systems, population evolution, diffusion, etc. — just replace animate_sin with the corresponding equation.

Installation:

pip install matplotlib numpy
Back to the blog