3D Visualization#

For 3D visualization, it is nice to be able to interactively change the view point by clicking and dragging.

In Jupyter Notebook before version 7, it could be done by the magic command:
%matplotlib notebook

In Jupyter Lab and recent Jupyter Nnotebook, you can do that by installing ipympl and the magic command:
%matplotlib widget

import numpy as np
import matplotlib.pyplot as plt
#%matplotlib notebook  
%matplotlib widget

Lines and Points in 3D#

You can create a 3D axis by projection='3d' option.

# spiral data
t = np.linspace(0, 20, 100)
x = t*np.sin(t)
y = t*np.cos(t)
# create a figure and 3D axes
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.plot(x, y, t);
plt.xlabel('x')
plt.ylabel('y')
ax.set_zlabel('t');  # There is no plt.zlabel() function
# You can make a figure and an axis in one line:
ax = plt.figure().add_subplot(projection='3d')
# scatter plot with x value mapped to color
ax.scatter(x, y, t, c=t)
plt.xlabel('x'); plt.ylabel('y'); ax.set_zlabel('t');

Surface plot#

x = np.linspace(-5, 5, 25)
y = np.linspace(-5, 5, 25)
X, Y = np.meshgrid(x, y)
Z = X*Y
ax = plt.figure().add_subplot(projection='3d')
ax.plot_surface(X, Y, Z)
plt.xlabel('x'); plt.ylabel('y'); ax.set_zlabel('z');

You can color the surface by the height.

ax = plt.figure().add_subplot(projection='3d')
# map Z value to 'viridis' colormap
ax.plot_surface(X, Y, Z, cmap='viridis')
plt.xlabel('x'); plt.ylabel('y'); ax.set_zlabel('z');

surface by wire frame#

ax = plt.figure().add_subplot(projection='3d')
# wireframe plot
ax.plot_wireframe(X, Y, Z)
plt.xlabel('x'); plt.ylabel('y'); ax.set_zlabel('z');

3D vector field by quiver( )#

x = np.linspace(-30, 30, 11)
y = np.linspace(-30, 30, 11)
z = np.linspace(0, 30, 11)
X, Y, Z = np.meshgrid(x, y, z)
#print(X)
# Lorenz attractor
p=10; r=28; b=8/3;
dX = p*(Y - X)  # dx/dt
dY = -X*Z + r*X - Y # dy/dt
dZ = X*Y - b*Z   # dz/dt
ax = plt.figure(figsize=(8,8)).add_subplot(111, projection='3d')
ax.quiver(X, Y, Z, dX, dY, dZ, length=0.01)
plt.xlabel('x'); plt.ylabel('y'); ax.set_zlabel('z');

For more advanced 3D visualization, you may want to use a specialized library like mayavi https://docs.enthought.com/mayavi/mayavi/