avatarRukshan Pramoditha

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

2606

Abstract

teractive</i></b> plots that are <b><i>not</i></b> <b><i>embedded</i></b> within the notebook. A separate window will pop up. You can get the same interactivity as above.</li></ul><p id="5fce">In Matplotlib, 3D plots can be enabled by importing the <code>mplot3d</code> toolkit that comes with Matplotlib installation.</p><div id="c3b7"><pre><span class="hljs-keyword">from</span> mpl_toolkits <span class="hljs-keyword">import</span> mplot3d</pre></div><p id="c83c">After importing <code>mplot3d</code>, we need to create a 3-dimensional axes (a subplot on the figure or canvas) as follows:</p><div id="89d1"><pre><span class="hljs-attr">ax</span> = plt.axes(projection=<span class="hljs-string">'3d'</span>)</pre></div><p id="5cd6">Here is the code for an empty 3D plot.</p><div id="6054"><pre><span class="hljs-keyword">import</span> matplotlib.pyplot <span class="hljs-keyword">as</span> plt <span class="hljs-title">from</span> mpl_toolkits <span class="hljs-keyword">import</span> mplot3d</pre></div><div id="213f"><pre><span class="hljs-attr">fig</span> = plt.figure(figsize=(<span class="hljs-number">9</span>, <span class="hljs-number">6</span>)) <span class="hljs-attr">ax</span> = plt.axes(projection=<span class="hljs-string">'3d'</span>)</pre></div><figure id="b5a8"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*-7KrgtXnPjMVRcXGGS8zcg.png"><figcaption>An empty 3D plot (Image by author)</figcaption></figure><p id="dcef">First, we imported the <code>pyplot</code> submodule from Matplotlib. Then, we enabled 3D plots by importing the <code>mplot3d</code> submodule. After that, we created the <b><i>Figure</i></b> (fig) object by specifying the size in inches. It acts as the canvas on which we create the plot or <b><i>Axes </i></b>(ax) object. Note that we haven’t added the <b><i>Axis</i></b> (x, y, z-axis) objects and any interactivity to the plot yet.</p><p id="4091">Now, we’ll add data to the empty plot and make a scatterplot by using the <b>scatter3D</b> method of the <b><i>ax</i></b> object. We’ll also add <b><i>Axis</i></b> (x, y, z-axis) objects to the plot. Here, we use synthetic (simulated) data generated by the NumPy <b>random</b> function.</p><div id="e674"><pre><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np</pre></div><div id="3ad6"><pre><span class="hljs-built_in">np</span>.<span class="hljs-built_in">random</span>.seed(<span class="hljs-number">3</span>) y = <span class="hljs-built_in">np</span>.<span class="hljs-built_in">random</span>.<span class="hljs-built_in">random</span>(<span class="hljs-numbe

Options

r">100</span>) x = <span class="hljs-built_in">np</span>.<span class="hljs-built_in">random</span>.<span class="hljs-built_in">random</span>(<span class="hljs-number">100</span>) z = <span class="hljs-built_in">np</span>.<span class="hljs-built_in">random</span>.<span class="hljs-built_in">random</span>(<span class="hljs-number">100</span>)</pre></div><div id="4d2d"><pre>ax.scatter3D(x, y, z, <span class="hljs-attribute">color</span>=<span class="hljs-string">'red'</span>)</pre></div><div id="34a8"><pre>ax.set_title(<span class="hljs-string">"3D scatterplot"</span>, <span class="hljs-attribute">pad</span>=25, <span class="hljs-attribute">size</span>=15) ax.set_xlabel(<span class="hljs-string">"X"</span>) ax.set_ylabel(<span class="hljs-string">"Y"</span>) ax.set_zlabel(<span class="hljs-string">"Z"</span>)</pre></div><figure id="8c26"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*OC4RCQpUJJh1wp6serHN9A.png"><figcaption>A 3D scatterplot (Image by author)</figcaption></figure><p id="7ce9">Note that we haven’t added any interactivity to the plot yet. To add interactivity, you should add <b>%matplotlib notebook </b>or <b>%matplotlib qt </b>at the<b> </b>beginning of the code.</p><div id="979c"><pre>%matplotlib qt <span class="hljs-keyword">import</span> matplotlib.pyplot <span class="hljs-keyword">as</span> plt ...</pre></div><p id="fe97">Here is the interactive pop-up window.</p><figure id="b3ea"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*qYLlLylvNGRaC8BxwZ11ag.png"><figcaption>3D scatterplot — interactive window (Image by author)</figcaption></figure><p id="cf91">When you move the cursor over the window, the plot will rotate. You can also zoom and resize the plot by using the available tools within the window.</p><p id="b3d5">This is the end of today’s post.</p><p id="5ea7"><b>Please let me know if you’ve any feedback</b>.</p><p id="82f3">Meanwhile, you can <a href="https://rukshanpramoditha.medium.com/membership"><b>sign up for a membership</b></a> to get full access to every story I write and I will receive a portion of your membership fee.</p><p id="7bac">Thank you so much for your continuous support! See you in the next story. Happy learning to everyone!</p><p id="7708">Special credit goes to <a href="https://unsplash.com/@bernardhermant?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Bernard Hermant<b></b></a><b> </b>on Unsplash,<b> </b>who provides me with a nice cover image for this post.</p><p id="d4c3"><a href="undefined">Rukshan Pramoditha</a> <b>2021–12–11</b></p></article></body>

Creating Interactive 3D Plots in Matplotlib

By using Matplotlib magic commands and object-oriented API

Photo by Bernard Hermant on Unsplash (modified by author)

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 mplot3d

After importing mplot3d, we need to create a 3-dimensional axes (a subplot on the figure or canvas) as follows:

ax = plt.axes(projection='3d')

Here is the code for an empty 3D plot.

import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
fig = plt.figure(figsize=(9, 6))
ax = plt.axes(projection='3d')
An empty 3D plot (Image by author)

First, we imported the pyplot submodule from Matplotlib. Then, we enabled 3D plots by importing the mplot3d submodule. After that, we created the Figure (fig) object by specifying the size in inches. It acts as the canvas on which we create the plot or Axes (ax) object. Note that we haven’t added the Axis (x, y, z-axis) objects and any interactivity to the plot yet.

Now, we’ll add data to the empty plot and make a scatterplot by using the scatter3D method of the ax object. We’ll also add Axis (x, y, z-axis) objects to the plot. Here, we use synthetic (simulated) data generated by the NumPy random function.

import numpy as np
np.random.seed(3)
y = np.random.random(100)
x = np.random.random(100)
z = np.random.random(100)
ax.scatter3D(x, y, z, color='red')
ax.set_title("3D scatterplot", pad=25, size=15)
ax.set_xlabel("X") 
ax.set_ylabel("Y") 
ax.set_zlabel("Z")
A 3D scatterplot (Image by author)

Note that we haven’t added any interactivity to the plot yet. To add interactivity, you should add %matplotlib notebook or %matplotlib qt at the beginning of the code.

%matplotlib qt
import matplotlib.pyplot as plt
...

Here is the interactive pop-up window.

3D scatterplot — interactive window (Image by author)

When you move the cursor over the window, the plot will rotate. You can also zoom and resize the plot by using the available tools within the window.

This is the end of today’s post.

Please let me know if you’ve any feedback.

Meanwhile, you can sign up for a membership to get full access to every story I write and I will receive a portion of your membership fee.

Thank you so much for your continuous support! See you in the next story. Happy learning to everyone!

Special credit goes to Bernard Hermant on Unsplash, who provides me with a nice cover image for this post.

Rukshan Pramoditha 2021–12–11

Matplotlib
Plotting
3d Plot
Data Visualization
Interactive Plots
Recommended from ReadMedium