Introduction
The init function sets the starting state for an animation. It prepares the plot before the animation frames update.
Jump into concepts and practice - no test required
The init function sets the starting state for an animation. It prepares the plot before the animation frames update.
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.
def init(): line.set_data([], []) return line,
def init(): scatter.set_offsets([]) return scatter,
This program animates a sine wave moving horizontally. The init function clears the line data before animation starts.
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()
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.
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.
init function in a matplotlib.animation.FuncAnimation?init function is called once to set the starting state of the plot elements before the animation frames begin.init prepares the plot initially.init function for FuncAnimation?init function takes no arguments and returns an iterable of plot elements to be animated.line, (a tuple with one element) is correct to enable blitting and animation updates.import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots()
line, = ax.plot([], [], 'r-')
xdata, ydata = [], []
def init():
line.set_data([], [])
return line,
def update(frame):
xdata.append(frame)
ydata.append(frame ** 2)
line.set_data(xdata, ydata)
return line,
ani = FuncAnimation(fig, update, frames=range(3), init_func=init, blit=True)
plt.show()init function clears the line data to empty lists, so the plot starts empty.init function used in FuncAnimation:def init():
line.set_data([], [])
plt.show()
return line,plt.show() displays the plot window and blocks code execution until closed.plt.show() inside init stops the animation setup and prevents frames from updating.FuncAnimation. How should you write the init function to properly initialize both lines for blitting?line1 and line2 must have their data cleared to empty lists.line1, line2, as a tuple is required for blitting to update both lines properly.