0
0
Matplotlibdata~5 mins

Init function for animation in Matplotlib

Choose your learning style9 modes available
Introduction

The init function sets the starting state for an animation. It prepares the plot before the animation frames update.

When you want to clear or reset the plot before each animation starts.
When you need to set initial data or styles for animated objects.
When you want to improve animation performance by initializing static parts once.
When using FuncAnimation in matplotlib to create smooth animations.
Syntax
Matplotlib
def init():
    # set initial state of plot elements
    return plot_elements,

The init function returns the plot elements that will be updated.

It is passed to FuncAnimation as the init_func parameter.

Examples
Clears the line data to start empty.
Matplotlib
def init():
    line.set_data([], [])
    return line,
Resets scatter plot points to empty.
Matplotlib
def init():
    scatter.set_offsets([])
    return scatter,
Sample Program

This program animates a sine wave moving horizontally. The init function clears the line data before animation starts.

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

fig, ax = plt.subplots()
line, = ax.plot([], [], 'r-')
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1, 1)

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

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

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

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

Always return a tuple of plot elements from the init function, even if it has one element (add a comma).

The init function helps avoid flickering by setting a clean start.

Summary

The init function sets the starting state of the animation.

It is passed to FuncAnimation as init_func.

It should return the plot elements that will be animated.