Animation — FuncAnimation
5.4.18· Coding › Scientific Computing (Python)
YEH TOOL EXIST KYU KARTA HAI?
YEH PRECISELY KYA HAI?
FRAME LOOP ACTUALLY KAISE CHALTA HAI (timing derive karo)
"Prove" karne ke liye koi equation nahi hai, lekin hum frame schedule ko first principles se derive kar sakte hain taaki kuch bhi magic na lage.

Worked Example 1 — ek travelling sine wave (canonical pattern)
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots()
ax.set_xlim(0, 2*np.pi) # Why: set limits ONCE so blitting can cache background
ax.set_ylim(-1.1, 1.1)
x = np.linspace(0, 2*np.pi, 400)
line, = ax.plot([], [], lw=2) # Why: create the artist ONCE, empty for now
def init():
line.set_data([], []) # Why: clean background; defines what "before frame 0" looks like
return line, # Why: blit needs the changed artists
def update(frame): # frame = 0,1,2,... from frames=...
y = np.sin(x - 0.1*frame) # Why: shift phase by frame → wave moves right
line.set_data(x, y) # Why: MUTATE existing artist, don't create a new one
return line, # Why: tell blit what to redraw
anim = FuncAnimation(fig, update, frames=200, init_func=init,
interval=20, blit=True) # 1000/20 = 50 FPS
plt.show()
# anim.save("wave.mp4", fps=50) # or "wave.gif"line, = ... aur return line, mein comma kyun? ax.plot lines ki ek list return karta hai; line, single element ko unpack karta hai. return line, ek 1-tuple banata hai — blit ek iterable of artists expect karta hai.
Worked Example 2 — frames as a generator (variable data per frame)
def frame_gen(): # Why: when each frame needs custom values, not just 0..N
t = 0.0
while t < 6.28:
yield t # this value becomes `frame` in update
t += 0.05
def update(t):
line.set_data(x, np.sin(x - t))
return line,
anim = FuncAnimation(fig, update, frames=frame_gen,
init_func=init, interval=30, blit=True, save_count=200)save_count kyun? Ek generator ki length unknown hoti hai; saving ke waqt, matplotlib ko pata hona chahiye kitne frames grab karne hain — save_count ise cap karta hai.
Worked Example 3 — EK SE ZYADA artist animate karna (jaise ek moving dot + trail)
line, = ax.plot([], [], 'b-')
dot, = ax.plot([], [], 'ro')
def update(i):
xi = x[:i]
line.set_data(xi, np.sin(xi)) # growing trail
dot.set_data([x[i]], [np.sin(x[i])]) # Why: lists, because set_data wants sequences
return line, dot # Why: return ALL changed artists for blitDono kyun return karein? Blit exactly wahi redraw karta hai jo tum return karte ho; ek bhool jao aur woh frozen dikhega.
Recall Feynman: ek 12-saal-ke bachche ko samjhao
Ek flip-book imagine karo. Har page lagbhag same drawing hai, lekin ball thodi si nudge hui hai. Pages fast palto aur ball flying lagti hai. FuncAnimation ek robot hai jo tumhara flip-book pakad ke rakhta hai. Tum ise EK rubber-stamp function dete ho jo kehta hai "page number n ke liye, ball yahan rakho," aur ek stopwatch jo kehta hai "har 20 milliseconds mein palto." Robot saari flipping karta hai. Trick: tum har baar nayi ball nahi draw karte — tum bas usi ball ko slide karte ho, isliye itna fast hai.
Active recall
What does FuncAnimation repeatedly call to produce each frame?
func ko, har frame ke liye ek baar, usi persistent figure par.With blit=True, what must init_func and func return?
return line,).Convert interval=25 ms to FPS.
Why create the line artist OUTSIDE the update function?
set_data se ek artist ko mutate karo, naye artists pile up karne ke bajaye (blitting valid aur memory flat rehti hai).Why must you keep a reference like anim = FuncAnimation(...)?
What does the trailing comma do in line, = ax.plot(...)?
ax.plot jo single-element list return karta hai, use line variable mein unpack karta hai.When frames is a generator, why pass save_count?
save_count matplotlib ko batata hai saving ke waqt kitne frames capture karne hain.How do you save an animation to mp4?
anim.save("out.mp4", fps=...) (ffmpeg chahiye) ya .gif (pillow/imagemagick chahiye).Total time for N=200 frames at interval=20ms (one pass)?
Connections
- Matplotlib Figure and Axes — woh canvas jise FuncAnimation update karta hai.
- Artists in Matplotlib —
Line2D,set_data, blitting. - Generators in Python —
framesargument ke liye use hote hain. - Event Loops / GUI backends — woh timer jo frames drive karta hai.
- NumPy linspace and broadcasting — per-frame arrays generate karna.
- Saving figures and ffmpeg — mp4/gif mein export karna.