Skip to content
Home » matplotlib Part 27 – 3D Points and Lines

matplotlib Part 27 – 3D Points and Lines

Spread the love

3D Points and Lines

Now that you know what 3D projection is, it’s time to actually plot something. Let’s start with something simple like 3D points and lines. As you remember, in 2D we use the ax.plot method to plot lines and the ax.scatter method to plot points. They both have counterparts in 3D, ax.plot3D and ax.scatter3D respectively.

So, without further ado, let’s plot a line in 3D. Let’s use some trigonometry to plot a spiral.

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

fig, ax = plt.subplots(subplot_kw={'projection': '3d'})

# Let's define the data first.
z = np.linspace(0, 30, 1000)
x = np.sin(z)
y = np.cos(z)

# Let's plot.
ax.plot3D(x, y, z, 'g')
Out[1]:
[<mpl_toolkits.mplot3d.art3d.Line3D at 0x17f1fc8b888>]

And now let’s plot some points. We can use the same example as before, but let’s reduce the number of points to 200 so that we can see them as separate points.

In [2]:
fig, ax = plt.subplots(subplot_kw={'projection': '3d'})

# Let's define the data first.
z = np.linspace(0, 30, 200)
x = np.sin(z)
y = np.cos(z)

# Let's plot.
ax.scatter3D(x, y, z, color='r')
Out[2]:
<mpl_toolkits.mplot3d.art3d.Path3DCollection at 0x17f20d32e08>

As you can see, the points that are further away from us in the 3D space are more faded that the ones closer to us.

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