0
0
Matplotlibdata~5 mins

Animation update function in Matplotlib

Choose your learning style9 modes available
Introduction

An animation update function changes the picture step-by-step to create moving images.

When you want to show how data changes over time.
When you want to make a graph that moves or updates automatically.
When you want to explain a process visually with changing pictures.
When you want to create a simple video from data points.
When you want to make your data story more interesting with motion.
Syntax
Matplotlib
def update(frame_number):
    # change plot elements here
    return updated_elements

The function takes a frame number that tells which step of the animation is running.

It must return the parts of the plot that change, so matplotlib knows what to redraw.

Examples
Update the y-values of a line for each frame.
Matplotlib
def update(i):
    line.set_ydata(data[i])
    return line,
Move points in a scatter plot to new positions each frame.
Matplotlib
def update(frame):
    scatter.set_offsets(new_positions[frame])
    return scatter,
Sample Program

This program makes a simple moving sine wave animation. The update function shifts the wave horizontally over time.

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

x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)

fig, ax = plt.subplots()
line, = ax.plot(x, y)

# Update function changes the y data to create a moving wave

def update(frame):
    line.set_ydata(np.sin(x + frame / 10))
    return line,

ani = FuncAnimation(fig, update, frames=100, interval=50, blit=True)
plt.show()
OutputSuccess
Important Notes

Always return the updated plot elements as a tuple or list.

Use the frame number to control how the plot changes over time.

Setting blit=True makes the animation faster by redrawing only changed parts.

Summary

The update function changes the plot for each animation frame.

It receives a frame number to know which step to show.

Return the changed plot parts so matplotlib can redraw them.