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 0x10ee759d0>]
![_images/8bba08d511fb3fec916e9a0f9b01eb8af1a463e1ab70e6861059a46ddc94ba1b.png](_images/8bba08d511fb3fec916e9a0f9b01eb8af1a463e1ab70e6861059a46ddc94ba1b.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 0x10eee8a40>
![_images/ab37460e618ef8f22992610129f4eacc2e16e00f321aae68328dbe5323dc237e.png](_images/ab37460e618ef8f22992610129f4eacc2e16e00f321aae68328dbe5323dc237e.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 0x10efc9310>
![_images/bfab31859764a6a0c8fef4b8834bb33f53032de4a1d848911dfc83c2e4967ceb.png](_images/bfab31859764a6a0c8fef4b8834bb33f53032de4a1d848911dfc83c2e4967ceb.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/29b13f759407ddb63a281ae531e8b12b138c8505f603465e1b3ea4255a9dfaf5.png](_images/29b13f759407ddb63a281ae531e8b12b138c8505f603465e1b3ea4255a9dfaf5.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 0x10f1908f0>
![_images/0094c36078d60f3db68eb2f6e624998c7cebfd403b5760240443cf058ed18b6a.png](_images/0094c36078d60f3db68eb2f6e624998c7cebfd403b5760240443cf058ed18b6a.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 0x10efd8ef0>
![_images/a22b441e1e1902453e034791ac27c822ad5e613cae8d609f4255c5e0ab7c2826.png](_images/a22b441e1e1902453e034791ac27c822ad5e613cae8d609f4255c5e0ab7c2826.png)
For more advanced 3D visualization, you may want to use a specialized library like mayavi
https://docs.enthought.com/mayavi/mayavi/