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
#But for this static book, we use regular inline mode.
import numpy as np
import matplotlib.pyplot as plt
#%matplotlib notebook
%matplotlib widget
Lines and Points in#
You can create a 3D axis by projection='3d'
option.
# spiral data
x = np.linspace(0, 20, 100)
y = x*np.sin(x)
z = x*np.cos(x)
# create a figure and 3D axes
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.plot(x, y, z);
# 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, z, c=x);
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);
You can color the surface by the height.
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# map Z value to 'viridis' colormap
ax.plot_surface(X, Y, Z, cmap='viridis');
surface by wire frame#
# make a 3D axis in one line
ax = plt.figure().add_subplot(111, projection='3d')
# wireframe plot
ax.plot_wireframe(X, Y, Z);
3D vector field by quiver( )
#
x = np.linspace(-5, 5, 10)
y = np.linspace(-5, 5, 10)
z = np.linspace(-5, 5, 10)
X, Y, Z = np.meshgrid(x, y, z)
#print(X)
# tornado
U = Y*Z # dx/dt
V = -X*Z # dy/dt
W = Z # dz/dt
ax = plt.figure().add_subplot(111, projection='3d')
ax.quiver(X, Y, Z, U, V, W, length=0.1);
For more advanced 3D visualization, you may want to use a specialized library like mayavi
https://docs.enthought.com/mayavi/mayavi/