3D Visualization#

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

import numpy as np
import matplotlib.pyplot as plt

The magic command %matplotlib notebook allows you to interactively change the viewpoint by clicking and dragging.
But for this static book, we use regular inline mode.

#%matplotlib notebook  
%matplotlib inline

Lines and Points in 3D#

# 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)
[<mpl_toolkits.mplot3d.art3d.Line3D at 0x112860390>]
_images/407104cb032247751262670db1b76027f74a0e6fea3b94d7862b3a321af47c0e.png
# 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)
<mpl_toolkits.mplot3d.art3d.Path3DCollection at 0x112a86150>
_images/2693ebcdb9b4d3460e70b8c218d67e44ce3bec00539b1416849c0b94576f87d1.png

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)
<mpl_toolkits.mplot3d.art3d.Poly3DCollection at 0x112aedfd0>
_images/7dd7bf98b7a1e5171669a41c407b6fb244e9ac5d6885dda5e30b73b632852751.png

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');
_images/4e91ba9a644fe674b28cdaa6507b11c16b86d7e149b286bae86200149180f07f.png

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)
<mpl_toolkits.mplot3d.art3d.Line3DCollection at 0x112cafd10>
_images/d860e237e283997fa6884e2aff76c46732f78522baa086067410389b74cb247e.png

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)
<mpl_toolkits.mplot3d.art3d.Line3DCollection at 0x112dab910>
_images/2f7e88ed9731dffaa82b2bf772f47b69e64b42770f3ccbaa514986130fe2372a.png

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