If you are viewing this file in preview mode, some links won't work. Find the fully featured Jupyter Notebook file on the website of Prof. Jens Flemming at Zwickau University of Applied Sciences. This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

3D plots

Matplotlib comes without native support for 3-dimensional plots. But there is an extension ('toolkit') for 3D plots: Mplot3d. This toolkit is part of the Matplotlib standard installation.

Basics

For 3d plotting we need an Axes3D object. This can either be created explicitly by plt3d.axes3d.Axes3D(fig) or implicitly by choosing projection='3d' in Figure.add_axes and similar functions. Automatic creation is preferred in newer versions of Mplot3d.

Now ax is of type Axes3d instead of Axes.

Plotting is very similar to 2d plots. Here is a 3d line plot:

Mplot3d uses the Matplotlib API to draw its 3d plots. All arguments not processed by Mplot3d are passed on to Matplotlib. Thus, many properties like line style and color can be set in exactly the same way as in Matplotlib.

Axes3D objects can be configured in the same way as Axes objects. Functions set_xlim, set_ylim, set_zlim, set_title and axis labeling work as expected.

Several plot types are available. Some of them provide additional features in their 3d variant. For example, scatter has a boolean argument depthshade, which by default is True and modifies the scatter points' color to give an appearance of depth. If color encodes an important feature, set depthshade=False.

Camera configuration

Initial position of the view can be set with azim and elev arguments when creating the Axes3D object. Simply pass them to Figure.add_axes or similar functions. The proj_type arguments switches between perspective (default) and orthogonal projection.

When plotting in a simple Python shell, Mplot3d/Matplotlib create a figure window which allows for rotating the plot by mouse. Example: rotate.py.

To get this feature in a Jupyter notebook add the IPython magic %matplotlib notebook.

Exercises

  1. Have a look at the documentation of %matplotlib.
  2. Get an overview of Axes3D object methods.
  3. Understand the Python code
    means = [[5, 0, 0], [-5, 2, 0], [0, -3, 5]] # mean vectors
    covs = [[[1, 1, 0], [1, 1, 0], [0, 0, 1]],
         [[10, 2, 0], [2, 10, 2], [0, 2, 10]],
         [[0.1, 0, 0], [0, 3, 3], [0, 3, 7]]] # covariance matrices
    ns = [100, 1000, 100] # cloud sizes
    
    and use numpy.multivariate_normat to generate three point clouds from means and covs with ns points. Plot these clouds in a 3d scatter plot with different color for each cloud and add plots of their projections to the coordinate planes. Solution