Create a Matplotlib 3D Scatter Animation in Python

Working on a data visualization project where I needed to show how data points move in 3D space over time. I wanted a smooth 3D scatter animation that could rotate and update dynamically.

The challenge was that while Matplotlib makes it easy to plot static 3D graphs, animating them isn’t as straightforward. So, I decided to experiment and share the exact steps I used to create a 3D scatter animation in Python using Matplotlib.

In this tutorial, I’ll walk you through everything, from setting up your environment to writing the full Python code that generates a beautiful rotating 3D scatter animation.

What is a 3D Scatter Animation in Python?

In Python, a 3D scatter animation is a dynamic visualization where points in 3D space change their positions (or the camera view rotates) over time.

This type of animation is perfect for visualizing data that evolves, like tracking the movement of drones, weather patterns, or stock market simulations over time.

Using Matplotlib’s animation module and mpl_toolkits.mplot3d, we can create such animations easily once we understand the basic structure.

Use Matplotlib for 3D Scatter Animations

While there are other Python libraries like Plotly and Mayavi, I prefer Matplotlib because:

  • It’s built into most Python environments.
  • It integrates well with NumPy and Pandas.
  • It’s lightweight and easy to customize.

Most importantly, it allows full control over animation frames, making it ideal for both beginners and advanced users.

Step 1 – Import Required Python Libraries

Before we start coding, let’s import all the necessary modules.

We’ll use:

  • Matplotlib for plotting
  • NumPy for numerical data generation
  • FuncAnimation from matplotlib.animation for creating the animation

Here’s the first part of our Python code:

# Import necessary libraries
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.animation import FuncAnimation

These imports form the foundation for our 3D animation setup.

Step 2 – Create Sample 3D Data Using Python

Next, we need some data to visualize.

In this example, I’ll generate random 3D coordinates that simulate moving points, imagine tracking multiple drones flying over a U.S. city.

# Create random 3D data points
num_points = 100
frames = 100

# Generate random coordinates
x = np.random.rand(num_points)
y = np.random.rand(num_points)
z = np.random.rand(num_points)

Here, we’re creating 100 points that will move across 100 frames of animation.

Step 3 – Set Up the Matplotlib 3D Figure

Now, we’ll create the 3D figure and axes using Matplotlib’s figure() and add_subplot() methods.

# Create a 3D figure
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')

# Set axis labels
ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis')
ax.set_zlabel('Z Axis')
ax.set_title('Matplotlib 3D Scatter Animation in Python')

This step sets up the 3D environment where our scatter points will move.

Step 4 – Create the Initial Scatter Plot

Before animating, we need an initial scatter plot to display the first frame.

# Create initial scatter plot
scat = ax.scatter(x, y, z, c='blue', s=50)

This line plots all points in blue with a size of 50.

Step 5 – Define the Update Function for Animation

The most important part of any animation is the update function. This function will be called repeatedly to update the scatter points’ positions for each frame.

# Define the update function
def update(frame_number):
    # Update the data points
    new_x = x + np.sin(frame_number / 10) * 0.1
    new_y = y + np.cos(frame_number / 10) * 0.1
    new_z = z + np.sin(frame_number / 15) * 0.1

    # Update scatter plot data
    scat._offsets3d = (new_x, new_y, new_z)

    # Rotate the view for better visualization
    ax.view_init(elev=30, azim=frame_number)
    return scat,

Here’s what’s happening:

  • We slightly shift the x, y, and z coordinates each frame to simulate motion.
  • We rotate the camera (azim) to create a dynamic 3D effect.

Step 6 – Create the Animation Using FuncAnimation

Now that we have the update function, we can use FuncAnimation to bring our 3D scatter plot to life.

# Create the animation
ani = FuncAnimation(fig, update, frames=frames, interval=100, blit=False)

# Display the animation
plt.show()

This will generate a smooth animation where the points appear to move and rotate in 3D space.

Full Working Python Code Example

Here’s the complete Python code for your reference. You can copy and run it directly in your IDE or Jupyter Notebook.

# Matplotlib 3D Scatter Animation in Python
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.animation import FuncAnimation

# Step 1: Generate random 3D data
num_points = 100
frames = 100
x = np.random.rand(num_points)
y = np.random.rand(num_points)
z = np.random.rand(num_points)

# Step 2: Create a 3D figure
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis')
ax.set_zlabel('Z Axis')
ax.set_title('Matplotlib 3D Scatter Animation in Python')

# Step 3: Initial scatter plot
scat = ax.scatter(x, y, z, c='blue', s=50)

# Step 4: Define the update function
def update(frame_number):
    new_x = x + np.sin(frame_number / 10) * 0.1
    new_y = y + np.cos(frame_number / 10) * 0.1
    new_z = z + np.sin(frame_number / 15) * 0.1
    scat._offsets3d = (new_x, new_y, new_z)
    ax.view_init(elev=30, azim=frame_number)
    return scat,

# Step 5: Create and display the animation
ani = FuncAnimation(fig, update, frames=frames, interval=100, blit=False)
plt.show()

You can see the output in the screenshot below.

Matplotlib 3D Scatter Animation in Python

This code will produce a rotating 3D scatter animation where all points move slightly with each frame.

Alternative Method – Save the Animation as a Video or GIF

Sometimes, you may want to export your animation to share it in presentations or reports.

You can easily save it as an MP4 or GIF using the following Python code:

# Save the animation as a video file
ani.save('3d_scatter_animation.mp4', writer='ffmpeg', fps=30)

Make sure you have FFmpeg installed on your system. You can install it using:

pip install ffmpeg

This will create a high-quality MP4 video file of your 3D scatter animation.

Customize the Matplotlib 3D Scatter Animation

You can enhance your Python animation by:

  • Changing colors dynamically based on data values.
  • Adjusting marker sizes for better visibility.
  • Adding labels or legends for clarity.

For example, to color points based on the Z-axis value:

scat = ax.scatter(x, y, z, c=z, cmap='viridis', s=60)

This makes your animation more visually appealing and informative.

Common Issues and Fixes

Here are a few common issues you might face while creating 3D scatter animations in Python:

1. Animation not displaying:
If you’re using Jupyter Notebook, add this line before plt.show():

%matplotlib notebook

2. Animation lagging:
Try reducing the number of points or frames to improve performance.

3. FFmpeg not found:
Ensure FFmpeg is installed and added to your system path.

Practical Example – Visualize Drone Movements in the USA

Let’s say you’re analyzing drone flight paths across New York City. Each point represents a drone’s position, and the animation shows how they move over time.

By using the same Python code, you can replace random values with actual GPS data to visualize real-world movement patterns.

This makes the animation not just visually appealing but also insightful for data analysis and presentations.

Conclusion

Creating a Matplotlib 3D scatter animation in Python may seem complex at first, but once you understand the structure, it’s surprisingly simple and powerful.

With just a few lines of Python code, you can bring static data to life, whether you’re visualizing drone paths, weather patterns, or any 3D dataset.

Other Python tutorials you may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.