Skip to content

nachiket-1/Python-animations-for-beginners

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 

Repository files navigation


Python Matplotlib Jupyter Kaggle License


"Animation is not the art of drawings that move, but the art of movements that are drawn." — Norman McLaren


Turn static charts into living, breathing visualizations — from zero to solar system in one notebook. 🚀


Open Notebook in Kaggle to watch the animation--> Open in Kaggle


📖 About

This notebook teaches Python animation from absolute scratch, with zero prior experience required. Every concept is introduced visually with code you can immediately run, tweak, and experiment with.

Whether you're a student wanting to make your data science projects stand out, or a developer curious about how animated visualizations work — this guide has you covered.


🗺️ Table of Contents


📦 What's Inside

# Section Topics Covered Difficulty
1 Setup & Theory How FuncAnimation works, library imports, dark theme setup 🟢 Easy
2 Moving Dot FuncAnimation basics, set_data(), frame logic 🟢 Easy
3 Sine Wave Animating lines, travelling waves, glow effects, live text 🟡 Medium
4 Bouncing Ball Physics (gravity, damping), state dictionaries, collision detection 🟡 Medium
5 Bar Chart Race ax.clear() pattern, sorting, dynamic labels, year counter 🟠 Intermediate
6 Solar System Multiple objects, orbital math, trail history, starfield 🔴 Advanced
7 Saving Animations GIF (pillow), MP4 (ffmpeg), interactive HTML 🟡 Medium

🎬 Animations Preview

🔵  Moving Dot          ──────●──────────────────────────→
〰️  Sine Wave           ∿∿∿∿∿∿∿∿∿∿∿∿∿∿∿∿∿∿∿∿∿∿∿∿∿∿∿∿→
⚽  Bouncing Ball       ●                 (gravity + bounce)
                            ●         ●
                                ● ●
📊  Bar Chart Race     TechCorp ██████████████████ $312B ↑
                       DataPy   ████████████ $198B
                       CloudX   ██████████ $175B ↓
🌌  Solar System         ·  ·  ☉  ·  · ·  (orbiting planets)

⚡ Quick Start

Option 1 — Kaggle (Recommended, No Setup)

Open in Kaggle

  1. Go to kaggle.com/codeNew Notebook
  2. Click File → Import Notebook
  3. Upload python_animations_for_beginners_1.ipynb
  4. Click Run All ▶️

Option 2 — Google Colab

Open In Colab

  1. Go to colab.research.google.com
  2. File → Upload notebook
  3. Upload the .ipynb file and run!

Option 3 — Run Locally

git clone https://github.com/nachiket-1/python-animations-guide.git
cd python-animations-guide
pip install -r requirements.txt
jupyter notebook python_animations_for_beginners.ipynb

🧠 How Animation Works

The core idea behind every animation in this notebook:

┌─────────────────────────────────────────────────────────┐
│                                                         │
│   Frame 0  →  Frame 1  →  Frame 2  →  Frame 3  →  ...  │
│                                                         │
│   update() is called once per frame, automatically     │
│   You just define: "what does frame N look like?"      │
│                                                         │
└─────────────────────────────────────────────────────────┘
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()
line, = ax.plot([], [])

def update(frame):          # ← This runs for EVERY frame
    # Change something...
    line.set_data(x, y)
    return line,

ani = FuncAnimation(
    fig,
    update,           # Your update function
    frames=100,       # Total number of frames
    interval=50,      # Milliseconds between frames
    blit=True         # Faster rendering
)

That's the entire pattern. Everything else in this notebook builds on this foundation.


📋 Requirements

matplotlib>=3.5.0
numpy>=1.21.0
IPython>=7.0.0
pillow>=9.0.0       # for saving GIFs

Install with:

pip install -r requirements.txt

✅ All dependencies come pre-installed on Kaggle and Google Colab — no setup needed!


🏁 Run on Kaggle

All libraries in this notebook are pre-installed on Kaggle. Just:

  1. Upload the notebook
  2. Set the accelerator to None (CPU is fine)
  3. Click Run All

To save outputs (GIFs, MP4s), they'll appear in /kaggle/working/ and can be downloaded from the output panel.


💻 Run Locally

Prerequisites

  • Python 3.8 or higher
  • Jupyter Notebook or JupyterLab

Step-by-step

# 1. Clone the repository
git clone https://github.com/YOUR_USERNAME/python-animations-guide.git
cd python-animations-guide

# 2. (Optional) Create a virtual environment
python -m venv venv
source venv/bin/activate      # macOS/Linux
venv\Scripts\activate         # Windows

# 3. Install dependencies
pip install -r requirements.txt

# 4. Launch Jupyter
jupyter notebook

# 5. Open the notebook and run cells with Shift+Enter

🔑 Key Concepts

blit=True vs ax.clear()

Method When to Use Speed
blit=True + set_data() Lines, dots, simple shapes that update in place ⚡ Fast
ax.clear() + redraw all Bar charts, complex layouts that change structure 🐢 Slower but flexible

Frame → Time Conversion

# Control animation speed by converting frames to time
t = frame * 0.1          # Slow
t = frame * 0.5          # Medium  
t = frame * 1.0          # Fast

# FPS is controlled by `interval` (milliseconds per frame)
interval=16   # ≈ 60 FPS
interval=33   # ≈ 30 FPS
interval=50   # = 20 FPS
interval=100  # = 10 FPS

State Management

# Use a dict so update() can modify values across frames
state = {'x': 0, 'vy': 0}

def update(frame):
    state['vy'] -= GRAVITY    # Persists between frames!
    state['x']  += state['vx']

🧪 Experiment Ideas

After going through the notebook, try these challenges:

  • 🌀 Lissajous Curve — plot (sin(at + δ), sin(bt)) over time — creates beautiful shapes
  • 🎯 Pong Game — two paddles, one bouncing ball, collision detection
  • 🌡️ Live Data Chart — animate a line that reads from a live list
  • 🕊️ Boids Simulation — flocking behaviour (birds/fish) with simple rules
  • 🌊 Double Pendulum — chaotic physics in ~30 lines
  • 📡 Radar Sweep — rotating line with a fading arc trail

💾 Saving Animations

# Save as GIF (works on Kaggle out of the box)
ani.save('animation.gif', writer='pillow', fps=25, dpi=80)

# Save as MP4 (requires ffmpeg)
ani.save('animation.mp4', writer='ffmpeg', fps=30, dpi=150)

# Save as self-contained HTML
ani.save('animation.html', writer='html')

# Show inside Jupyter notebook
from IPython.display import HTML
HTML(ani.to_jshtml())

💡 On Kaggle: Saved files appear under Output in the right panel and can be downloaded directly.


🚀 What's Next?

Once you've mastered matplotlib.animation, explore these libraries:

Library Best For Complexity
plotly Interactive web animations with sliders 🟡 Medium
manim Math explanation videos (3Blue1Brown style) 🔴 Advanced
pygame Real-time games and interactive simulations 🟠 Intermediate
celluloid Simpler wrapper around FuncAnimation 🟢 Easy
p5py Creative coding & generative art 🟡 Medium

📁 Repository Structure

python-animations-guide/
│
├── 📓 python_animations_for_beginners.ipynb   ← Main notebook
├── 📋 README.md                                ← This file
├── 📦 requirements.txt                         ← Dependencies
└── 🖼️ assets/                                  ← (optional) Preview GIFs
    ├── sine_wave.gif
    ├── bouncing_ball.gif
    └── solar_system.gif

🤝 Contributing

Found a bug? Have a cool animation idea to add? Contributions are welcome!

  1. Fork the repository
  2. Create a new branch: git checkout -b feature/my-animation
  3. Add your changes
  4. Submit a Pull Request

📄 License

This project is licensed under the MIT License — free to use, modify, and share.


Made with ❤️ and Python

If this helped you, consider giving the repo a ⭐ — it helps others find it!

About

A hands-on beginner's guide to creating animations in Python using Matplotlib. Covers FuncAnimation, sine waves, bouncing ball physics, bar chart races, and a solar system simulation — with clean code, visual explanations, and experiment challenges at every step.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors