Home » Tutorial on Matplotlib Animations in Python

Tutorial on Matplotlib Animations in Python

Spring Framework Basics Video Course
Java SE 11 Programmer I [1Z0-815] Practice Tests
Java SE 11 Programmer II [1Z0-816] Practice Tests
Oracle Java Certification
Java SE 11 Developer (Upgrade) [1Z0-817]
1 Year Subscription

Matplotlib animations allow you to create dynamic visualizations that can reveal trends over time or highlight specific data changes.

Using the FuncAnimation class from matplotlib.animation, you can create animations by repeatedly updating elements in your plot.

In this tutorial, we’ll explore how to create animations in Matplotlib, covering the basics and more advanced animations, along with various customization options.

1. Setting Up a Simple Animation

The FuncAnimation function animates a plot by repeatedly calling a function that updates the plot elements.

Basic Structure of FuncAnimation:

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

# Initialize figure and axis
fig, ax = plt.subplots()
x_data, y_data = [], []

# Initialize line object
line, = ax.plot([], [], lw=2)

# Set axis limits
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)

# Function to initialize the background of the animation
def init():
    line.set_data([], [])
    return line,

# Update function
def update(frame):
    x_data.append(frame)
    y_data.append(frame ** 2)  # Example: y = x^2
    line.set_data(x_data, y_data)
    return line,

# Call FuncAnimation
ani = FuncAnimation(fig, update, frames=range(10), init_func=init, blit=True)
plt.show()

Here:

  • init_func: The initialization function to set up the background of the animation.
  • update: The function that updates the data for each frame.
  • frames: The number of frames in the animation.
  • blit=True: Optimizes rendering for animations.

2. Animating a Sine Wave

Let’s animate a sine wave by updating its y-values over time.

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

# Create figure and axis
fig, ax = plt.subplots()
x = np.linspace(0, 2 * np.pi, 100)
line, = ax.plot(x, np.sin(x))

# Set axis limits
ax.set_ylim(-1.5, 1.5)

# Update function
def update(frame):
    line.set_ydata(np.sin(x + frame / 10))  # Update y-data with phase shift
    return line,

# Create animation
ani = FuncAnimation(fig, update, frames=range(100), blit=True)
plt.show()

In this example, the update function shifts the sine wave by modifying the phase, creating a “moving wave” effect.

3. Animating a Scatter Plot

In this example, we’ll animate a scatter plot by updating the position of points over time.

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

# Create figure and axis
fig, ax = plt.subplots()
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)

# Initialize scatter plot
x_data = np.random.rand(10) * 10
y_data = np.random.rand(10) * 10
scat = ax.scatter(x_data, y_data)

# Update function
def update(frame):
    global x_data, y_data
    x_data += np.random.randn(10) * 0.1  # Small random movements
    y_data += np.random.randn(10) * 0.1
    scat.set_offsets(np.c_[x_data, y_data])
    return scat,

# Create animation
ani = FuncAnimation(fig, update, frames=100, blit=True)
plt.show()

This example uses set_offsets to update the positions of the points in the scatter plot with each frame, creating a “random walk” effect.

4. Animating a Bar Chart

Bar charts are useful for showing changes in categories over time. Here’s an example of animating a bar chart.

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

# Data
categories = ['A', 'B', 'C', 'D']
y_data = np.random.randint(1, 10, size=len(categories))

# Create figure and bar plot
fig, ax = plt.subplots()
bars = ax.bar(categories, y_data)

# Update function
def update(frame):
    global y_data
    y_data = np.random.randint(1, 10, size=len(categories))
    for bar, new_height in zip(bars, y_data):
        bar.set_height(new_height)
    return bars

# Create animation
ani = FuncAnimation(fig, update, frames=50, blit=True)
plt.show()

This example animates a bar chart by changing the heights of the bars in each frame.

5. Customizing Animation with Intervals and Saving

The interval parameter controls the delay between frames, and the repeat parameter specifies if the animation should loop.

To save an animation as a .gif or .mp4, you’ll need to use the save method.

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

# Create figure and line
fig, ax = plt.subplots()
x = np.linspace(0, 2 * np.pi, 100)
line, = ax.plot(x, np.sin(x))

ax.set_ylim(-1.5, 1.5)

# Update function
def update(frame):
    line.set_ydata(np.sin(x + frame / 10))
    return line,

# Create animation with custom interval and save
ani = FuncAnimation(fig, update, frames=100, interval=50, repeat=True)
ani.save('sine_wave.gif', writer='imagemagick')  # Requires ImageMagick
plt.show()

6. Animating Multiple Elements

Here, we’ll animate both a line and scatter points on the same plot.

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

# Create figure and axis
fig, ax = plt.subplots()
x = np.linspace(0, 2 * np.pi, 100)
line, = ax.plot(x, np.sin(x), label='Sine Wave')
scatter, = ax.plot([], [], 'ro')

ax.set_ylim(-1.5, 1.5)

# Initialize scatter plot
def init():
    scatter.set_data([], [])
    return line, scatter

# Update function
def update(frame):
    line.set_ydata(np.sin(x + frame / 10))
    scatter.set_data(x[frame % len(x)], np.sin(x[frame % len(x)]))
    return line, scatter

# Create animation
ani = FuncAnimation(fig, update, frames=100, init_func=init, blit=True)
plt.show()

In this example, both the line plot and the scatter point are animated, with the scatter point moving along the sine wave as the line oscillates.

7. Advanced Animation with 3D Plot

Matplotlib supports animations in 3D as well. Here’s an example with a rotating 3D plot.

from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

# Generate data for 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
t = np.linspace(0, 20, 1000)
x = np.sin(t)
y = np.cos(t)
z = t

# Initialize plot
line, = ax.plot(x, y, z, color='purple')

# Update function to rotate the view
def update(frame):
    ax.view_init(elev=10., azim=frame)
    return line,

# Create animation
ani = FuncAnimation(fig, update, frames=np.arange(0, 360, 5), blit=True)
plt.show()

In this 3D example, the update function rotates the view angle by adjusting the azimuth (azim) to create a rotating effect.

Summary

In this tutorial, we covered how to create various animations in Matplotlib:

  1. Basic line animations.
  2. Animating a sine wave with phase shifts.
  3. Creating animated scatter plots with changing positions.
  4. Animating a bar chart by updating bar heights.
  5. Customizing animations with intervals and saving them.
  6. Animating multiple elements on the same plot.
  7. Rotating 3D animations.

 

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More