How to Create 3D Subplots in Matplotlib Python

I was working on a project where I needed to visualize multiple datasets in 3D using Python.
The challenge was to compare them side by side without switching between multiple plots.

That’s when I turned to Matplotlib subplots in 3D. This feature allows me to create multiple 3D axes in the same figure, which makes it easier to analyze data visually.

In this tutorial, I will share my firsthand experience of using Matplotlib subplot 3D in Python.
I’ll walk you through different methods, complete code examples, and tips that I personally use in real-world projects.

What is a 3D Subplot in Matplotlib Python?

A subplot in Matplotlib Python is simply a smaller plot inside a larger figure. When we extend this concept to 3D, we can display multiple 3D plots side by side or in a grid layout.

This is especially useful when working with data science or machine learning projects in the USA. For example, comparing 3D scatter plots of sales data across different states becomes much easier with subplots.

Import Required Libraries in Python

Before we start, let’s import the required libraries in Python. We mainly need matplotlib.pyplot and mpl_toolkits.mplot3d.

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

Here, I am also importing NumPy because it helps me generate sample data quickly. This way, I don’t need to rely on external datasets for explanations.

Method 1 – Create a Single 3D Subplot in Python

The first method is the simplest way to create a 3D subplot in Python. We use the projection=’3d’ argument while creating the subplot.

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

# Generate sample data
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))

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

# Plot surface
ax.plot_surface(X, Y, Z, cmap='viridis')

# Labels
ax.set_title("Single 3D Subplot Example")
ax.set_xlabel("X Axis")
ax.set_ylabel("Y Axis")
ax.set_zlabel("Z Axis")

plt.show()

You can see the output in the screenshot below.

Create 3D Subplots in Matplotlib Python

In this example, I created a 3D surface plot using sine values. This is a simple but effective way to start working with 3D subplots in Python.

Method 2 – Create Multiple 3D Subplots in One Row

Now let’s move to a more practical case where we need multiple 3D plots. I often use this when I want to compare two different datasets side by side.

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

# Sample data
x = np.linspace(-4, 4, 50)
y = np.linspace(-4, 4, 50)
X, Y = np.meshgrid(x, y)

Z1 = np.sin(X) * np.cos(Y)
Z2 = np.cos(X) * np.sin(Y)

# Create figure with two subplots
fig = plt.figure(figsize=(12,6))

# First subplot
ax1 = fig.add_subplot(121, projection='3d')
ax1.plot_surface(X, Y, Z1, cmap='plasma')
ax1.set_title("3D Subplot 1")

# Second subplot
ax2 = fig.add_subplot(122, projection='3d')
ax2.plot_surface(X, Y, Z2, cmap='cividis')
ax2.set_title("3D Subplot 2")

plt.show()

You can see the output in the screenshot below.

Matplotlib Python 3D Subplots

Here, I created two 3D subplots in a single row using Python. This layout is very useful when comparing models, like sales forecasts vs actual sales.

Method 3 – Create a Grid of 3D Subplots in Python

Sometimes, one row is not enough, and we need a grid of 3D subplots. In such cases, we can use the plt.subplots function with projection=’3d’.

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

# Sample data
x = np.linspace(-3, 3, 40)
y = np.linspace(-3, 3, 40)
X, Y = np.meshgrid(x, y)

Z1 = np.sin(X) + np.cos(Y)
Z2 = np.sin(X*Y)
Z3 = np.exp(-0.1*(X**2 + Y**2))
Z4 = np.tan(X*Y) / 10  # scaled down to avoid overflow

# Create 2x2 subplot grid
fig = plt.figure(figsize=(12,10))

# Subplot 1
ax1 = fig.add_subplot(221, projection='3d')
ax1.plot_surface(X, Y, Z1, cmap='viridis')
ax1.set_title("Z = sin(X) + cos(Y)")

# Subplot 2
ax2 = fig.add_subplot(222, projection='3d')
ax2.plot_surface(X, Y, Z2, cmap='plasma')
ax2.set_title("Z = sin(X*Y)")

# Subplot 3
ax3 = fig.add_subplot(223, projection='3d')
ax3.plot_surface(X, Y, Z3, cmap='cividis')
ax3.set_title("Z = exp(-0.1*(X^2 + Y^2))")

# Subplot 4
ax4 = fig.add_subplot(224, projection='3d')
ax4.plot_surface(X, Y, Z4, cmap='coolwarm')
ax4.set_title("Z = tan(X*Y)/10")

plt.tight_layout()
plt.show()

You can see the output in the screenshot below.

Matplotlib Python Create 3D Subplots

This method is powerful when you want to present multiple variations of a dataset. For example, I used this approach to show different mathematical models to a client in the USA.

Method 4 – Use 3D Scatter Plots in Subplots

Not all 3D visualizations are surface plots. Sometimes, scatter plots are more useful, especially when dealing with real-world datasets.

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

# Generate random data
np.random.seed(42)
x1, y1, z1 = np.random.rand(50), np.random.rand(50), np.random.rand(50)
x2, y2, z2 = np.random.rand(50), np.random.rand(50), np.random.rand(50)

# Create figure with two scatter subplots
fig = plt.figure(figsize=(12,6))

ax1 = fig.add_subplot(121, projection='3d')
ax1.scatter(x1, y1, z1, c='red', marker='o')
ax1.set_title("3D Scatter Subplot 1")

ax2 = fig.add_subplot(122, projection='3d')
ax2.scatter(x2, y2, z2, c='blue', marker='^')
ax2.set_title("3D Scatter Subplot 2")

plt.show()

You can see the output in the screenshot below.

How to Create 3D Subplots in Matplotlib Python

In this example, I created two 3D scatter subplots. This is very useful when comparing datasets like customer demographics across two different states in the USA.

Method 5 – Customize 3D Subplots in Python

Customizing the subplots makes them more readable and presentation-ready. We can adjust titles, axis labels, colors, and even add grid lines.

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

# Data
theta = np.linspace(0, 2*np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)

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

# Plot line
ax.plot(x, y, z, label='3D Spiral', color='green')
ax.set_title("Customized 3D Subplot")
ax.set_xlabel("X Axis")
ax.set_ylabel("Y Axis")
ax.set_zlabel("Z Axis")
ax.legend()

plt.show()

Here, I added labels, a legend, and a custom color to the 3D subplot. This makes the visualization more professional and easier to interpret.

Key Points to Remember

  • Always use projection=’3d’ when creating 3D subplots in Python.
  • Use fig.add_subplot(rows, cols, index, projection=’3d’) for multiple subplots.
  • plt.tight_layout() helps to avoid overlapping titles and labels.
  • Customize your plots with labels, legends, and colors for better readability.

When I first started using Matplotlib subplot 3D in Python, it felt overwhelming. But once I practiced with these methods, I realized how powerful and flexible it is.

Now, I regularly use 3D subplots to present insights to clients in the USA. It makes my reports more engaging and helps decision-makers understand data faster.

You may also read:

Leave a Comment

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.