0
0
Matplotlibdata~5 mins

FuncAnimation for dynamic plots in Matplotlib

Choose your learning style9 modes available
Introduction

FuncAnimation helps you make moving or changing plots. It shows how data changes over time.

To show how stock prices change minute by minute.
To display live sensor data updating every second.
To animate a mathematical function changing with time.
To visualize real-time weather changes like temperature or wind speed.
Syntax
Matplotlib
FuncAnimation(fig, func, frames=None, init_func=None, fargs=None, interval=200, repeat=True, blit=False)

fig: The figure object where the animation happens.

func: A function that updates the plot for each frame.

Examples
Animate 100 frames, updating every 100 milliseconds.
Matplotlib
ani = FuncAnimation(fig, update, frames=100, interval=100)
Animate 50 frames and stop after finishing.
Matplotlib
ani = FuncAnimation(fig, update, frames=range(50), repeat=False)
Use an init function to set up the plot and optimize redraws with blit.
Matplotlib
ani = FuncAnimation(fig, update, init_func=init, blit=True)
Sample Program

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.

Matplotlib
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()
OutputSuccess
Important Notes

Use blit=True to make animations smoother by only redrawing parts that change.

The init_func sets the starting state of the plot.

Use interval to control the speed of the animation in milliseconds.

Summary

FuncAnimation creates moving plots by repeatedly calling an update function.

You set how many frames and how fast the animation runs.

Use init_func and blit to improve animation performance.