Defining multiple plots to be animated with a for loop in Matplotlib

To define multiple plots to be animated with a for loop in matplotlib, you can animate different plot elements simultaneously. This technique is useful for creating complex visualizations where multiple data series or plot types change over time.

Steps to Create Multiple Animated Plots

  • Set the figure size and adjust the padding between subplots
  • Create a figure and add axes with appropriate limits
  • Initialize data arrays using NumPy
  • Create multiple plot elements (lines, bars, etc.)
  • Define an animation function that updates all elements in a loop
  • Use FuncAnimation to repeatedly call the update function
  • Display the animated figure

Example

Here's how to animate both line plots and bar charts simultaneously −

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

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(0, 100))

# Initialize data
N = 4
x = np.linspace(-5, 5, 100)

# Create multiple line plots
lines = [plt.plot(x, np.sin(x))[0] for _ in range(N)]

# Create bar chart
rectangles = plt.bar([0.5, 1, 1.5], [50, 40, 90], width=0.1)

# Combine all patches for blitting
patches = lines + list(rectangles)

def animate(i):
    # Animate each line plot
    for j, line in enumerate(lines):
        line.set_data([0, 2, i, j], [0, 3, 10 * j, i])
    
    # Animate each bar
    for j, rectangle in enumerate(rectangles):
        rectangle.set_height(i / (j + 1))
    
    return patches

# Create animation
anim = animation.FuncAnimation(fig, animate, frames=100, interval=20, blit=True)

plt.show()

How It Works

The animation function animate(i) is called for each frame, where i represents the current frame number. Inside this function:

  • Line Animation: Each line's data is updated using set_data() with coordinates that change based on frame number and line index
  • Bar Animation: Each bar's height is modified using set_height() with values that depend on the frame number
  • Return Patches: All modified plot elements are returned for efficient blitting

Key Parameters

Parameter Purpose Example Value
frames Number of animation frames 100
interval Delay between frames (milliseconds) 20
blit Optimize drawing for better performance True

Conclusion

Using for loops within the animation function allows you to efficiently update multiple plot elements simultaneously. This approach is ideal for creating complex animated visualizations with different plot types that change together over time.

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

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements