Animation avec Matplotlib#

Vous découvrirez ici comment créer une animation avec Python et Matplotlib.

Animation avec effacement#

Animation avec le module animation de Matplotlib#

Nous allons utiliser la fonction FuncAnimation() du module animation.

Exemple

Dans ce script, nous allons définir une fonction animate() qui met à jour la courbe pour chaque image.

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

k = 2*np.pi
w = 2*np.pi
dt = 0.01

xmin = 0
xmax = 3
nbx = 151

x = np.linspace(xmin, xmax, nbx)

fig = plt.figure() # initialise la figure
line, = plt.plot([], []) 
plt.xlim(xmin, xmax)
plt.ylim(-1, 1)

def animate(i): 
    t = i * dt
    y = np.cos(k*x - w*t)
    line.set_data(x, y)
    return line,
 
ani = animation.FuncAnimation(fig, animate, frames=100,
                              interval=1, blit=True, repeat=False)
plt.show()

La fonction FuncAnimation() dispose d’un argument avec une étiquette appelée interval, qui est le temps en millisecondes entre deux appels de la fonction de mise à jour, ici animate().

Ancien exemple

Nous présentons ici une approche qui se retrouve dans de nombreux anciens exemples disponibles sur internet.

Nous y définissons une fonction init() qui est affectée au paramètre init_func de FuncAnimation(). Ceci entraine un appel de cette fonction avant la première image. Cette approche n’est toutefois pas indispensable pour les usages qui sont réalisés le plus souvent.

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

k = 2*np.pi
w = 2*np.pi
dt = 0.01

xmin = 0
xmax = 3
nbx = 151

x = np.linspace(xmin, xmax, nbx)

fig = plt.figure() # initialise la figure
line, = plt.plot([], []) 
plt.xlim(xmin, xmax)
plt.ylim(-1, 1)

def init():
    line.set_data([], [])
    return line,

def animate(i): 
    t = i * dt
    y = np.cos(k*x - w*t)
    line.set_data(x, y)
    return line,
 
ani = animation.FuncAnimation(fig, animate, init_func=init, frames=100, 
                              interval=1, blit=True, repeat=False)

plt.show()

Animation sans le module animation#

Nous présentons ici une technique d’animation plus basique qui n’utilise pas le module animation. Cette technique n’est pas recommandée mais elle peut servir pour des animations simples. Pour des animations plus élaborées, l’utilisation du module animation est préférable.

import numpy as np
import matplotlib.pyplot as plt

k = 2*np.pi
w = 2*np.pi
dt = 0.01

x = np.linspace(0, 3, 151)

for i in range(50):
    t = i * dt
    y = np.cos(k*x - w*t)
    if i == 0:
        line, = plt.plot(x, y)
    else:
        line.set_data(x, y)
    plt.pause(0.01) # pause avec duree en secondes
    
plt.show()

Note

Quand il est seulement nécessaire de modifier les valeurs de y, il est possible d’utiliser set_ydata(y) au lieu de set_data(x, y).

Animation sans effacement#

import numpy as np
import matplotlib.pyplot as plt

k = 2*np.pi
w = 2*np.pi
dt = 0.01  

x = np.linspace(0, 3, 151)

for i in range(50):
    t = i * dt
    y = np.cos(k*x - w*t)
    plt.plot(x, y)
    plt.pause(0.01) # pause avec duree en secondes

plt.show()