Fundamentals 3 min read
Create Stunning 3D Plots in Python with Matplotlib: Lines, Scatter, and Surfaces
Learn how to generate 3D line, scatter, and surface visualizations in Python using Matplotlib's mplot3d toolkit, with step-by-step code examples that create a canvas, produce data arrays, and render interactive plots for enhanced data analysis and presentation.
Model Perspective
Model Perspective
3D Line Plot
<code># 3D line plot
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
# generate canvas
fig = plt.figure()
ax = fig.gca(projection='3d') # specify 3D projection
# generate (x, y, z) data
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z ** 2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
# draw plot (same plot function as 2D)
ax.plot(x, y, z)
plt.show()
</code>3D Scatter Plot
<code># 3D scatter plot
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
# generate canvas
fig = plt.figure()
ax = fig.gca(projection='3d') # specify 3D projection
# draw 100 red points
x1 = np.random.random(100) * 20
y1 = np.random.random(100) * 20
z1 = x1 + y1
ax.scatter(x1, y1, z1, c='r', marker='o')
# draw 100 blue points
x2 = np.random.random(100) * 20
y2 = np.random.random(100) * 20
z2 = x2 + y2
ax.scatter(x2, y2, z2, c='b', marker='^')
plt.show()
</code>3D Surface Plot
<code># 3D surface plot
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
# generate canvas
fig = plt.figure()
ax = fig.gca(projection='3d') # specify 3D projection
# generate data (x, y, z)
x = np.arange(-5, 5, 0.25)
y = np.arange(-5, 5, 0.25)
x, y = np.meshgrid(x, y) # key: use meshgrid to create coordinate grid
z = np.sin(np.sqrt(x ** 2 + y ** 2))
# use plot_surface function (cmap=cm.coolwarm sets color map)
surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm)
plt.show()
</code>Written by
Model Perspective
Insights, knowledge, and enjoyment from a mathematical modeling researcher and educator. Hosted by Haihua Wang, a modeling instructor and author of "Clever Use of Chat for Mathematical Modeling", "Modeling: The Mathematics of Thinking", "Mathematical Modeling Practice: A Hands‑On Guide to Competitions", and co‑author of "Mathematical Modeling: Teaching Design and Cases".
0 followers
Reader feedback
How this landed with the community
Rate this article
Was this worth your time?
Discussion
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.