How to pass arguments to animation.FuncAnimation() in Matplotlib?

To pass arguments to animation.FuncAnimation() for a contour plot in Matplotlib, we can use the fargs parameter or create a closure. This allows us to pass additional data or parameters to the animation function.

Basic Animation Example

Let's start with a simple contour animation using random data ?

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

# Create random data
data = np.random.randn(800).reshape(10, 10, 8)
fig, ax = plt.subplots(figsize=(7, 4))

def animate(i):
    ax.clear()
    ax.contourf(data[:, :, i])
    ax.set_title(f'Frame {i}')

# Create animation
ani = animation.FuncAnimation(fig, animate, frames=8, interval=500, repeat=True)
plt.tight_layout()
plt.show()

Method 1: Using fargs Parameter

Pass additional arguments to the animation function using fargs ?

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

# Create sample data
x = np.linspace(0, 2*np.pi, 50)
y = np.linspace(0, 2*np.pi, 50)
X, Y = np.meshgrid(x, y)

fig, ax = plt.subplots(figsize=(7, 4))

def animate(frame, X, Y, speed, amplitude):
    ax.clear()
    Z = amplitude * np.sin(X + frame * speed) * np.cos(Y + frame * speed)
    contour = ax.contourf(X, Y, Z, levels=20, cmap='viridis')
    ax.set_title(f'Animated Contour - Frame {frame}')
    return contour

# Pass arguments using fargs
speed = 0.2
amplitude = 2.0
ani = animation.FuncAnimation(
    fig, animate, frames=30, 
    fargs=(X, Y, speed, amplitude), 
    interval=100, repeat=True
)

plt.tight_layout()
plt.show()

Method 2: Using Closure

Create a closure to capture variables in the animation function ?

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

# Create data
t = np.linspace(0, 2*np.pi, 100)
x = np.linspace(0, 4*np.pi, 100)
X, T = np.meshgrid(x, t)

fig, ax = plt.subplots(figsize=(7, 4))

def create_animate_function(frequency, wave_speed):
    def animate(frame):
        ax.clear()
        Z = np.sin(frequency * X - wave_speed * frame * 0.1)
        contour = ax.contourf(X, T, Z, levels=15, cmap='plasma')
        ax.set_title(f'Wave Animation - Frequency: {frequency}')
        ax.set_xlabel('Position')
        ax.set_ylabel('Time')
        return contour
    return animate

# Create animation function with captured variables
freq = 2
speed = 1.5
animate_func = create_animate_function(freq, speed)

ani = animation.FuncAnimation(
    fig, animate_func, frames=50, 
    interval=100, repeat=True
)

plt.tight_layout()
plt.show()

Method 3: Using Lambda Function

Use a lambda function to pass arguments inline ?

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

# Create grid
x = np.linspace(-2, 2, 50)
y = np.linspace(-2, 2, 50)
X, Y = np.meshgrid(x, y)

fig, ax = plt.subplots(figsize=(7, 4))

def animate_with_params(frame, X, Y, radius_factor, rotation_speed):
    ax.clear()
    # Create rotating spiral pattern
    angle = frame * rotation_speed
    R = np.sqrt(X**2 + Y**2)
    Z = np.sin(radius_factor * R + angle) * np.exp(-R/3)
    
    contour = ax.contourf(X, Y, Z, levels=20, cmap='coolwarm')
    ax.set_title(f'Rotating Spiral - Frame {frame}')
    return contour

# Use lambda to pass parameters
radius_factor = 3.0
rotation_speed = 0.3

ani = animation.FuncAnimation(
    fig, 
    lambda frame: animate_with_params(frame, X, Y, radius_factor, rotation_speed),
    frames=40, interval=150, repeat=True
)

plt.tight_layout()
plt.show()

Comparison of Methods

Method Syntax Best For
fargs FuncAnimation(fig, func, fargs=(arg1, arg2)) Simple parameter passing
Closure def outer(): def inner(): ... Complex state management
Lambda lambda frame: func(frame, args) Quick inline solutions

Conclusion

Use fargs for simple parameter passing to animation functions. For complex scenarios with multiple parameters or state management, closures provide better organization and readability.

Updated on: 2026-03-25T23:47:06+05:30

940 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements