Worked examples — Animation — FuncAnimation
5.4.18 · D3· Coding › Scientific Computing (Python) › Animation — FuncAnimation
Pehle ek waada: har symbol earn kiya hua hai. interval ek number hai milliseconds mein — flip-book ke do flips ke beech ka waqt. frames hai "page numbers" (ya values) ki list jo robot walk karta hai. FPS hai ek second mein kitne pages flip hote hain. func (hum ise update bolenge) hai woh rubber stamp jo kehta hai "is page ke liye, picture AISE banao". Yeh chaar pictures apne dimaag mein rakkho.
Do aur chhoti cheezein hain jinhe hum baar baar use karenge, jo yahan, pehle use se pehle define ki gayi hain:
Scenario matrix
FuncAnimation ke baare mein har sawaal in cells mein se kisi ek mein aata hai. Neeche ke hamare examples mein se har ek un cells ke saath tagged hai jisme woh aata hai, aur saath milake sab ko cover karte hain.
| Axis | Cases jo cover karne hain |
|---|---|
| Frame source | integer N · explicit list/array · generator (unknown length) |
| Timing direction | diya interval → FPS/total time nikalo · diya FPS/time → interval nikalo |
| Blit | blit=True (artists return karne zaroor hain) · blit=False (return value ignore hota hai) |
| Artist count | ek artist · kai artists (line + dot) |
| Degenerate / limiting | frames=0 (empty) · interval=0 (jitna fast ho sake) · one-frame animation · generator jo kabhi nahi rukta |
| Saving | chosen fps par mp4 mein save karo · interval saving mein kyun ignore hota hai · generator + save_count |
| Word / exam twist | "mujhe 8-second clip chahiye" real problem · "meri window blank kyun hai?" bug-hunt |
Woh number jo timing ko ek saath jodhta hai, parent mein ek baar derive kiya gaya, yeh hai:
Example 1 — integer frames → FPS aur total time (cell: integer N · interval→FPS · one artist)
Forecast: padhne se pehle FPS guess karo. Kya 20 ms frames ke beech fast hai ya slow?
- Numbers padho.
interval = 20ms,N = 200frames. Yeh step kyun? Har timing problem numbers ko name karne se shuru hoti hai — kaun sa numberintervalhai aur kaun saN, taaki hum unhe mix na karein. - Pehli equation se FPS. . Yeh step kyun? "1000 ms mein kitne 20 ms slots fit hote hain?" — woh count hi frames-per-second hai.
- Doosri equation se total time. ms; bridge se convert karo: s. Yeh step kyun? Ek pass har frame ka chhota sa wait hai, end-to-end stack kiya — ms mein — phir 1000 se divide karke seconds mein padhte hain.
Verify: doosre form se cross-check karo: s. ✓ Units: . ✓
Example 2 — inverse: "mujhe exact-length clip chahiye" (cell: given FPS/time→interval · word problem · saving)
Forecast: kya file save karte waqt interval matter bhi karta hai?
- Frames = FPS × seconds. frames. Yeh step kyun? ko rearrange karne par milta hai — right side ke dono values pata hain.
- FPS se Interval. ms.
Yeh step kyun? Same pehli equation,
intervalke liye solve ki: slot length hai "ek second (1000 ms) ko FPS pieces mein baantna." - Saving
fpspass karta hai,intervalnahi.anim.save("clip.mp4", fps=60). Yeh step kyun? Parent note ka key rule: saving karte waqt, matplotlib frames ko seconds par space karta hai aurintervalignore karta hai (koi live GUI timer nahi obey karna). Dekho Saving figures and ffmpeg.
Verify: , ke saath: s exactly. ✓ Aur ms ms s live playback ke liye. ✓
Example 3 — frames ka array ek moving dot ko feed karta hai (cell: explicit array · many artists · blit=True)

Pehle data fix karo, taaki neeche har symbol concrete ho:
import numpy as np
x = np.linspace(0, 2*np.pi, 200) # 200 evenly-spaced x-values from 0 to 2π
# y at any x is np.sin(x); see [[NumPy linspace and broadcasting]]Toh ==x== ek NumPy array hai jisme se tak 200 evenly spaced numbers hain (`linspace` se bane), aur np.sin(x) matching heights ka array hai. x[:i] matlab "x ki pehli i entries" — ek slice.
Forecast: agar tum sirf dot return karo aur trail line bhool jao — screen par kya hoga?
- Dono artists ek baar, empty banaao.
line, = ax.plot([], [], 'b-')aurdot, = ax.plot([], [], 'ro'). Yeh step kyun? Parent ke rule ke mutabiq, artistsupdateke bahar bante hain aur andar sirf mutate hote hain — dekho Artists in Matplotlib. - Frame
idata slice karta hai. trail = pointsx[:i]; dot = single point(x[i], sin(x[i])). Yeh step kyun?x[:i]slice koike saath grow karna hi trail ko lengthen karta hai — figure dekho: mint trail left-se-right grow karti hai jabke coral dot uski tip par ride karta hai. - DONO artists return karo.
return line, dot. Yeh step kyun?blit=Trueke saath, matplotlib exactly wohi redraw karta hai jo tum return karte ho. Line chhod do aur trail freeze ho jaayegi.
Verify (sanity, no arithmetic): par, trail empty hai (x[:0]), dot par — ek single starting point, "motion se pehle frame" se match karta hai. Last par, x[:i] poora curve hai. ✓ Figure ke frames-side captions slice lengths confirm karte hain.
Example 4 — frames ke taur par ek generator, save_count ke saath (cell: generator · saving · unknown length)
Forecast: kya matplotlib ek generator ki length khud jaanta hai?
- Yields count karo. Values hain pehle tak par nahi including. Count .
Yeh step kyun?
while t < 6.28with step indices se tak yield karta hai (kyunki lekin ). Yeh 126 values hain. - Live playback theek hai — timer bas generator se naye
tvalues pull karta rehta hai jab tak woh exhaust na ho jaaye. Dekho Generators in Python. - Saving ko count chahiye. Ek generator ka koi
lennahi hota.save_count=200.saveko batata hai ki kitne frames pull karne hain uska upper bound. Yeh step kyun? Saver ko pehle se pata hona chahiye (ya cap hona chahiye) kitni images likhni hain; woh generator se puch nahi sakta "tum kitne lambe ho?"
Verify: ✓ aur ✓, toh exactly 126 frames. Kyunki , save_count=200 unhe saare capture kar leta hai gunjaaish ke saath. ✓
Example 5 — blit=False: return value matter karna band ho jaata hai (cell: blit off · one artist)
Forecast: kya return bhoolna blit=False animation ko tod dega?
blit=Falseke saath, poora axes har frame mein redraw hota hai. Return value ignore hoti hai. Yeh step kyun? Blitting woh single feature hai jo tumhare returned artists padhta hai (use pata hona chahiye ki cached background ke upar kya copy karna hai). No blit → kuch nahi return padhta.- Toh
return line,yahan harmless lekin optional hai. Ise rakhne ka matlab hai wahi code baad meinblit=Trueflip karne par bhi kaam karta hai. Yeh step kyun? Future-proofing: ek aadat (hamesha artists return karo) dono modes mein kaam karti hai. - Cost: slower, kyunki ticks/grid/labels har frame mein re-render hote hain — exactly woh kharcha jo blitting skip karne ke liye banaaya gaya tha.
Verify (behavioural): ek blit=False animation bina return statement ke phir bhi sahi animate karti hai (proves return ignore hoti hai); ek blit=True wali bina return ke raise/freeze karti hai (proves blit ise padhta hai). Yeh ek logic check hai, arithmetic nahi — asymmetry hi poora point hai.
Example 6 — degenerate: zero frames, one frame, interval 0 (cell: empty / single / limiting)

Forecast: kya frames=0 crash karta hai, freeze karta hai, ya static picture dikhata hai?
frames=0→ ek pass mein kuch move nahi karta.updatekabhi kisi frame value ke saath call nahi hota; tum sirf wohi dekhte ho joinit_funcne draw kiya tha (clean background jo humne upar define ki). s of motion. Yeh step kyun? ke saath doosri equation deti hai: koi frames nahi matlab koi animation time nahi guzra. Figure ka left panel sirf cleaninit_funcbackground dikhata hai.frames=1→ ek single flip.updateek baar run karta hai (frame0), phir (kyunkirepeat=Truedefault hai — woh loop-when-frames-run-out switch jo humne upar define kiya) woh ek frame hamesha ke liye loop karta hai, toh yeh still image jaisa lagta hai. . Yeh step kyun? Yeh sabse chhota non-empty case hai; useful hai test karne ke liye ki tumhare artists bilkul dikhte hain ya nahi.interval=0→ "backend jitna fast allow kare utna". mathematically undefined hai; practically GUI timer event loop jitni jaldi kar sake utni jaldi fire karta hai, toh real FPS formula se nahi, tumhare machine se cap hoti hai. Yeh step kyun? Yeh pehli equation ka limiting behaviour hai: jaise , FPS , lekin hardware ise clamp karta hai. Literal zero se kabhi apne dimaag mein divide mat karo — ise ek limit ki tarah padho.
Verify: (a) s ✓. (b) s ms single frame ke liye ✓. (c) limit check: jaise interval ms shrink hota hai, FPS rise karta hai, confirm karta hai FPS as interval . ✓
Example 7 — never-ending generator (cell: generator that never stops · limiting)
Forecast: kya live playback kabhi rukegi? Kya saving hamesha hang karegi?
- Live playback indefinitely chalta hai. Generator kabhi
StopIterationraise nahi karta, toh timer harintervalms mein nayetvalues pull karta rehta hai jab tak tum window band nahi karte. Yeh step kyun?FuncAnimationek pass tab rokta hai jab frame source exhaust ho jaaye; infinite source kabhi exhaust nahi hota.repeatirrelevant hai (koi "end" nahi hai loop karne ke liye), yeh bas ek endless stream hai. - Saving zaroor cap honi chahiye.
.saveimages likhne ke liye generator walk karta hai. Bina length aur binasave_countke, matplotlib nahi jaanta kab rokna hai — woh frames forever pull karne ki koshish karta rahega. Yeh step kyun? Yahi reason haisave_countexist karta hai (Example 4): yeh ek infinite generator ke liye mandatory hai.anim.save("out.mp4", fps=30, save_count=300)pehle 300 frames likhta hai aur rok deta hai. - Fix pattern. Ya toh generator finite banao (stop condition add karo) ya saving karte waqt hamesha
save_countpass karo. Yeh step kyun? Dono saver ko ek definite endpoint dete hain; finite generator live playback ko bhi naturally end karne deta hai.
Verify: save_count=300 aur fps=30 ke saath, saved clip length s hai — ek definite, finite file chahe generator infinite ho. ✓
Example 8 — classic "window blank hai" bug (cell: exam twist · degenerate reference-loss)
Forecast: bug update mein hai, interval mein hai, ya kahin aur?
- Missing assignment pakdo. Call result store nahi hua: koi
anim = ...nahi. Yeh step kyun?FuncAnimationek object return karta hai jo timer ka owner hai. Aur kuch ise alive nahi rakhta. - Python ise garbage-collect karta hai. Jaise hi unreferenced object collect hota hai, uska timer mar jaata hai — aur koi frames nahi. Yeh step kyun? Yeh event loop se jodta hai: timer ek live object hai; reference drop karo, heartbeat drop karo.
- Fix:
anim = FuncAnimation(...)auranimko scope mein rakkho (module-level ya apne function se return karo).
Verify (behavioural): identical code jo sirf anim = add karta hai woh animate karta hai; ise hatao toh blank window har baar reproduce hoti hai — reference ko sole cause ke roop mein isolate karta hai. ✓
Active recall
Connections
- Animation — FuncAnimation — parent: woh machine jinhe yeh scenarios exercise karti hain.
- Matplotlib Figure and Axes — woh canvas jo har frame mein update hota hai.
- Artists in Matplotlib —
Line2D,set_data, blit-return. - Generators in Python — Examples 4 & 7 ka frame source.
- Event Loops / GUI backends — Examples 6 & 8 ke peeche ka timer.
- NumPy linspace and broadcasting — per-frame arrays banana (Example 3 ka
x). - Saving figures and ffmpeg — Examples 2, 4 & 7 ka
.save.