The examples below show simple 3D plots using matplotlib. matplotlib's 3D capabilities were added by incorporating John Porter's mplot3d module, thus no additional download is required any more, the following examples will run with an up to date matplotlib installation. Note, this code is not supported in the matplotlib-0.98 branch, but you can use either the latest 0.99 release or the 0.91 maintenance version if you need this functionality. Alternatively, the Mayavi2 project provides a pylab-like API for extensive 3D plotting: http://code.enthought.com/projects/mayavi/docs/development/html/mayavi/mlab.html
Note that not all examples on this page are up to date, so some of them might not be working. For other examples, see http://matplotlib.sourceforge.net/examples/mplot3d/
3D Plotting examples:
1 from numpy import *
2 import pylab as p
3 #import matplotlib.axes3d as p3
4 import mpl_toolkits.mplot3d.axes3d as p3
5
6 # u and v are parametric variables.
7 # u is an array from 0 to 2*pi, with 100 elements
8 u=r_[0:2*pi:100j]
9 # v is an array from 0 to 2*pi, with 100 elements
10 v=r_[0:pi:100j]
11 # x, y, and z are the coordinates of the points for plotting
12 # each is arranged in a 100x100 array
13 x=10*outer(cos(u),sin(v))
14 y=10*outer(sin(u),sin(v))
15 z=10*outer(ones(size(u)),cos(v))
Wireframe (works on 0.87.5):
3D Plot:
1 # this connects each of the points with lines
2 fig=p.figure()
3 ax = p3.Axes3D(fig)
4 # plot3D requires a 1D array for x, y, and z
5 # ravel() converts the 100x100 array into a 1x10000 array
6 ax.plot3D(ravel(x),ravel(y),ravel(z))
7 ax.set_xlabel('X')
8 ax.set_ylabel('Y')
9 ax.set_zlabel('Z')
10 fig.add_axes(ax)
11 p.show()
Scatter (works on 0.87.5, shows some artefacts):
Surface (works on 0.87.5):
Contour3D (works on 0.87.5):
1 delta = 0.025
2 x = arange(-3.0, 3.0, delta)
3 y = arange(-2.0, 2.0, delta)
4 X, Y = p.meshgrid(x, y)
5 Z1 = p.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
6 Z2 = p.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
7 # difference of Gaussians
8 Z = 10.0 * (Z2 - Z1)
9 fig=p.figure()
10 ax = p3.Axes3D(fig)
11 ax.contour3D(X,Y,Z)
12 ax.set_xlabel('X')
13 ax.set_ylabel('Y')
14 ax.set_zlabel('Z')
15 p.show()
Contourf3D:
1 # in mplt3D change:
2 # levels, colls = self.contourf(X, Y, Z, 20)
3 # to:
4 # C = self.contourf(X, Y, Z, *args, **kwargs)
5 # levels, colls = (C.levels, C.collections)
6 fig=p.figure()
7 ax = p3.Axes3D(fig)
8 ax.contourf3D(X,Y,Z)
9 ax.set_xlabel('X')
10 ax.set_ylabel('Y')
11 ax.set_zlabel('Z')
12 fig.add_axes(ax)
13 p.show()
2D Contour Plots (work on 0.87.5):
For some other examples of 3d plotting capability, run the following commands. See the source of matplotlib/axes3d.py for more information: