This program animates a sine wave moving to the right. The update function shifts the wave by changing the phase. The plot updates every 50 milliseconds for 100 frames.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# Create figure and axis
fig, ax = plt.subplots()
# Set up a line object with empty data
line, = ax.plot([], [], lw=2)
# Set axis limits
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1, 1)
# Initialization function: plot background
def init():
line.set_data([], [])
return line,
# Update function: called for each frame
def update(frame):
x = np.linspace(0, 2*np.pi, 1000)
y = np.sin(x + 0.1 * frame)
line.set_data(x, y)
return line,
# Create animation
ani = FuncAnimation(fig, update, frames=100, init_func=init, interval=50, blit=True)
plt.show()