Skip to content
Home » matplotlib Part 26 – Axes3D and 3D Projection

matplotlib Part 26 – Axes3D and 3D Projection

Spread the love

Axes3D and 3D Projection

2D plots are great and in most cases they’re all you need. But if you need a 3D plot, matplotlib has this functionality too. In this lecture we’ll be talking about the basics of 3D plotting in matplotlib.

So, just like we used the Axes object for 2D plots, we must use an Axes3D object for 3D plots. The Axes3D class is defined in the mpl_toolkits.mplot3d module.

We can create the Axes3D object by passing the figure instance to its constructor, by calling the add_subplot method with the keyword argument projection set to ‘3d’ or by using the plt.subplots method with the subplot_kw argument set to {‘projection’: ‘3d’}.

Let’s now see how these three approaches work.

In [1]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np

# We need this for 3D.
from mpl_toolkits import mplot3d

# Let's create an empty 3D axes by passing the figure to the constructor of the Axes3D class.
# So, let's create the figure first.
fig = plt.figure()

# Now let's pass it to the Axes3D constructor.
ax = mplot3d.Axes3D(fig)
In [2]:
# Now let's do the same by calling the add_subplot method with the keyword argument projection set to '3d'.
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')
In [3]:
# Finally, let's re-create the empty axes by using the plt.subplots method with the subplot_kw argument 
# set to {'projection': '3d'}
fig, ax = plt.subplots(subplot_kw={'projection': '3d'})

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply