Matplotlib 3D Scatter Plot in Python

I’ve been working with Python for over a decade, and one of the most powerful tools I’ve found for visualizing complex data is Matplotlib’s 3D scatter plot. When you want to explore relationships between three variables simultaneously, nothing beats a well-crafted 3D scatter plot.

In this article, I’ll walk you through everything you need to know to create stunning 3D scatter plots in Python.

Let’s get in!

What Is a 3D Scatter Plot?

A 3D scatter plot displays data points in three-dimensional space, defined by x, y, and z coordinates. Unlike a simple 2D scatter plot, it allows you to see how three variables interact with each other visually. This is especially useful when you want to identify clusters, trends, or outliers in datasets with multiple features.

Method 1: Create a Basic 3D Scatter Plot

Let me start with the simplest way to plot a 3D scatter chart using Matplotlib.

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D  # Import 3D plotting toolkit
import numpy as np

# Sample data: Sales data for three products across different states
states = ['California', 'Texas', 'New York', 'Florida', 'Illinois']
sales_product_a = [250, 150, 200, 180, 220]
sales_product_b = [300, 170, 210, 190, 230]
sales_product_c = [280, 160, 190, 200, 210]

# Create 3D scatter plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

ax.scatter(sales_product_a, sales_product_b, sales_product_c, c='blue', marker='o')

ax.set_xlabel('Product A Sales')
ax.set_ylabel('Product B Sales')
ax.set_zlabel('Product C Sales')
ax.set_title('3D Scatter Plot of Sales Across States')

plt.show()

You can see the output in the screenshot below.

3d scatter plot python

This example uses sales figures for three products across several states. Each point in the plot represents sales numbers for all three products in a state.

  • It’s easy and quick to implement.
  • Great for exploring datasets with three numeric variables.
  • You can easily customize colors and markers.

Method 2: Add Color and Size to Represent Additional Variables

Sometimes, you want to show more than just three dimensions. One trick I often use is to encode a fourth variable using the color or size of the scatter points.

Here’s how to add color and size based on a fourth variable, such as the population of each state:

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

states = ['California', 'Texas', 'New York', 'Florida', 'Illinois']
sales_a = [250, 150, 200, 180, 220]
sales_b = [300, 170, 210, 190, 230]
sales_c = [280, 160, 190, 200, 210]
population = [39500000, 29000000, 19500000, 21500000, 12500000]  # population in millions

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Normalize population for marker size
sizes = np.array(population) / 1000000 * 100  # scale for visibility

scatter = ax.scatter(sales_a, sales_b, sales_c, s=sizes, c=population, cmap='viridis', alpha=0.7)

ax.set_xlabel('Product A Sales')
ax.set_ylabel('Product B Sales')
ax.set_zlabel('Product C Sales')
ax.set_title('3D Scatter Plot with Population as Color and Size')

fig.colorbar(scatter, ax=ax, label='Population')

plt.show()

You can see the output in the screenshot below.

matplotlib 3d scatter

Using color gradients and varying marker sizes, you can add more depth to your data story.

Method 3: Rotate and Animate the 3D Scatter Plot

Sometimes a static 3D plot isn’t enough to fully grasp the data structure. I often rotate the plot or create animations to get a better perspective.

Here’s a simple way to rotate your 3D scatter plot interactively:

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

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

ax.scatter(sales_a, sales_b, sales_c, c='red')

ax.set_xlabel('Product A Sales')
ax.set_ylabel('Product B Sales')
ax.set_zlabel('Product C Sales')

# Rotate the view
ax.view_init(elev=20, azim=45)  # Change elevation and azimuth angle

plt.show()

You can see the output in the screenshot below.

3d scatter plot matplotlib

If you want to create an animation that rotates the plot over time, you can use Matplotlib’s animation module. This is especially helpful when presenting to stakeholders who want to see the data from multiple angles.

Read Matplotlib Unknown Projection ‘3d’

Tips for Effective 3D Scatter Plots

  • Keep it simple: Avoid cluttering the plot with too many points or dimensions.
  • Use color wisely: Color can represent categories or continuous variables, but make sure it’s intuitive.
  • Label axes clearly: Since 3D plots can be complex, clear axis labels help viewers understand what they’re looking at.
  • Interactive plots: Consider using interactive backends or tools like Plotly if you want users to explore the data themselves.

I hope you found this guide helpful. 3D scatter plots are a powerful way to visualize multivariate data and uncover insights that might be hidden in 2D charts. With Matplotlib, you can create these visualizations quickly and customize them to fit your needs.

If you want to dive deeper, try combining these methods with real datasets from your work or interests. The best way to master 3D plotting is by practicing and experimenting.

You may also read:

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.