Celluloid: The Simplest Way to Animate Matplotlib Plots
Intro
A lightweight Python package called Celluloid makes it easy and quick to animate Matplotlib charts. With just a few lines of code, users may create fluid animations with Celluloid, in contrast to Matplotlib's built-in animation module, which requires sophisticated programming. It is perfect for viewing dynamic data because it captures frames with ease. We'll go over how to install it, its main characteristics, and useful applications in this blog.
Key Features of Celluloid
-
Camera Class for Frame Capture - Simplifies animation creation by capturing plot frames automatically.
from celluloid import Camera fig, ax = plt.subplots() camera = Camera(fig) for i in range(10): ax.plot([i], [i], 'ro') camera.snap() animation = camera.animate()
-
Seamless Matplotlib Integration - Works directly with existing Matplotlib code.
# Regular Matplotlib plot ax.plot(x, y, 'b-') # Add animation camera = Camera(fig) for frame in frames: ax.plot(updated_data) camera.snap()
-
Multi-Subplot Animations - Handles complex layouts with multiple subplots.
fig, (ax1, ax2) = plt.subplots(1, 2) camera = Camera(fig) for i in range(100): ax1.plot(x[:i], y1[:i]) ax2.plot(x[:i], y2[:i]) camera.snap()
-
Multiple Output Formats - Save as GIFs or MP4s.
animation.save('output.gif', writer='pillow', fps=20) animation.save('output.mp4', writer='ffmpeg', fps=20)
-
Real-Time Annotations - Add dynamic text and markers.
for i in range(100): ax.plot(x[i], y[i], 'ro') ax.text(x[i], y[i], f'Frame {i}') camera.snap()
-
3D Animation Support - Create complex 3D visualizations.
fig = plt.figure() ax = fig.add_subplot(111, projection='3d') camera = Camera(fig) for i in range(100): ax.plot(x[:i], y[:i], z[:i]) camera.snap()
-
Lightweight & Efficient - Minimal dependencies.
# Only requires: !pip install celluloid matplotlib
-
Smooth Transitions - Built-in interpolation between frames.
animation = camera.animate(interval=50, blit=True, repeat_delay=1000)
Installation
Follow these steps to install and use Celluloid:
# Step 1: Install Celluloid
pip install celluloid
Examples
Let us explore some of the features of Celluloid with some examples.
Visualising a Quadratic Function
import numpy as np
import matplotlib.pyplot as plt
from celluloid import Camera
# Create a figure and axis
fig, ax = plt.subplots()
# Create a camera to take snapshots of the figure
camera = Camera(fig)
# Define the x values
x = np.linspace(-10, 10, 400)
# Define the range of 'a' values to animate
a_values = np.linspace(-1, 1, 100)
# Loop through different 'a' values and plot the quadratic function
for a in a_values:
y = a * x**2 + 2 * x + 1 # Quadratic function y = ax^2 + bx + c
ax.plot(x, y, label=f'a = {a:.2f}')
ax.set_xlim(-10, 10)
ax.set_ylim(-10, 10)
ax.legend(loc='upper right')
camera.snap() # Take a snapshot for the animation
# Create the animation
animation = camera.animate()
plt.close(fig)
# Display the animation in the Colab notebook
from IPython.display import HTML
HTML(animation.to_html5_video())
Animating a Sine Wave
import numpy as np
import matplotlib.pyplot as plt
from celluloid import Camera
from IPython.display import HTML
from IPython.display import Image
import matplotlib.animation as animation
# Set up the figure and camera
fig, ax = plt.subplots()
camera = Camera(fig)
x = np.linspace(0, 4*np.pi, 100) # X values
for i in range(100):
y = np.sin(x + i * 0.1) # Shift sine wave over time
ax.plot(x, y, 'b') # Plot updated sine wave
camera.snap() # Capture frame
# Create animation
animation = camera.animate(interval=50) # Interval in milliseconds
plt.close(fig)
from IPython.display import HTML
HTML(animation.to_jshtml()) # Displays interactive animation
Stock Price Animation
import yfinance as yf
import matplotlib.pyplot as plt
from celluloid import Camera
# Fetch stock data
ticker = "AAPL" # Example: Apple Inc.
data = yf.download(ticker, start="2023-01-01", end="2023-10-01")
dates = data.index
prices = data['Close']
# Set up the plot and camera
fig, ax = plt.subplots(figsize=(10, 5))
camera = Camera(fig)
# Animate the stock price
for i in range(len(dates)):
ax.plot(dates[:i+1], prices[:i+1], color='blue', lw=2) # Plot up to the i-th point
ax.set_title(f'{ticker} Stock Price Animation')
ax.set_xlabel('Date')
ax.set_ylabel('Price (USD)')
ax.grid(True, linestyle='--', alpha=0.7)
camera.snap() # Capture the frame
# Create the animation
animation = camera.animate(interval=50)
# Display the animation
from IPython.display import HTML
HTML(animation.to_html5_video())
Real World Use Cases
- Educational Visualizations – Helps students and educators animate mathematical functions, physics simulations, and algorithm demonstrations for better understanding.
- Stock Market & Financial Analysis – Used to animate trends in stock prices, market fluctuations, and financial data over time.
- Climate & Weather Data Visualization – Useful for animating temperature changes, rainfall distribution, and climate patterns over different periods.
- Medical & Healthcare Analytics – Can be used to animate patient data trends, ECG waveforms, or disease spread over time.
- Social Media & Marketing Analytics – Visualizes audience engagement, campaign performance, and trends dynamically.
- Traffic & Navigation Data – Used for tracking vehicle movement, congestion trends, and route optimization analysis.
Conclusion
Celluloid simplifies and streamlines animating Matplotlib plots, making the development of complex code unnecessary. Data visualizations are easily brought to life using minimal commands. From presentations, through research, to artistic projects, Celluloid is an effective tool for seamless animations in Python.