Member-only story
Creating Interactive 3D Plots in Matplotlib
By using Matplotlib magic commands and object-oriented API

You’re already familiar with 2D (2-dimensional) plots where there are two dimensions that represent two variables in the dataset. When you want to plot data that have three variables, you need to create a 3D (3-dimensional) plot.
Matplotlib, the Python plotting library, provides useful tools and functions to create 3D plots for different purposes. Today, we will create a 3D scatterplot by using the Matplotlib object-oriented API. The interactivity is added to the plot by using an appropriate magic command.
Basically, Matplotlib provides two plotting APIs.
- The pyplot API — This contains MATLAB-style syntax and is not suitable for complex plots.
- The object-oriented API —This allows you to work directly with Figure (canvas), Axes (subplots on the canvas) and Axis (x, y, z-axis) objects and provides more control and customization over the plots. This is the API that we’ll use here to create 3D plots.
The interactivity of the plot depends on the type of IPython (Interactive Python) magic command we use. A magic command is a special command that IPython adds to get a useful task when working with an IPython notebook (e.g. Jupyter notebook). It begins with the % character.
The following three types of magic commands are often used when plotting with Matplotlib.
- %matplotlib inline — This is the default one. So, you don’t need to write this in your Jupyter notebook to add the function of this command. This will lead to creating static plots that are embedded within the notebook.
- %matplotlib notebook — This will lead to creating interactive plots that are embedded within the notebook. “Interactive” means that you can zoom, rotate and resize the plots by using the cursor.
- %matplotlib qt — This will lead to creating interactive plots that are not embedded within the notebook. A separate window will pop up. You can get the same interactivity as above.
In Matplotlib, 3D plots can be enabled by importing the mplot3d
toolkit that comes with Matplotlib installation.
from mpl_toolkits import…