3D Plotting with Matplotlib

Matplotlib was originally composed with only two-dimensional plotting in mind. Around the time of the 1.0 release, some three-dimensional plotting advantages were built on top of Matplotlib’s two-dimensional layout, and the effect is handy. Three-dimensional plots are enabled by importing all necessary libraries: Numpy, matplotlib and also import axes3d from mpl_toolkits.mplot.3d:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d

Once axes3d is imported, three-dimensional axes can be developed by passing the keyword projection='3d' to any of the normal axes creation routines:

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

Let’s create the data:

xs =[1,2,3,4,5,6,7,8,9,10]
ys =[51,5,1,2,15,4,1,22,4,8]
zs =[12,43,13,23,55,37,9,11,19,10]

xt =[-1,-2,-3,-4,-5,-6,-7,8,-9,-10]
yt =[-5,-6,-2,-3,-13,-4,-1,2,-4,-8]
zt =[-2,-3,-3,-3,-5,-7,9,-11,-9,-10]

Let’s plot the Data:

ax.scatter(xs, ys, zs, c='r', marker='o')
ax.scatter(xt, yt, zt, c='b', marker='^')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')