How to plot on the 3D axes

To insert something on the plot we've created, make the new axes and generate 500 random points with random x, y, and z positions:

# Add a 3D Scatterplot
x = np.random.normal(size=500)
y = np.random.normal(size=500)
z = np.random.normal(size=500)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x,y,z)

When we call scatter on this axis object, we get a 3D projected scatter plot, as shown here:

As we hover over this 3D scatter plot, we get a 3D Gaussian (essentially a ball of points). A 3D Gaussian approximates a lot of interesting phenomena; for example, it's a reasonable approximation of certain kinds of star clusters in astrophysics.

We will color these balls of points as we did with our standard scatter. This scatter actually behaves like the standard 2D version. So, let's first take the norm of x, y, and z, as shown in the following code:

# Add a 3D Scatterplot
x = np.random.normal(size=500)
y = np.random.normal(size=500)
z = np.random.normal(size=500)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x,y,z,c=np.linalg.norm([x,y,z], axis=0))

We get the output as shown in the following plot—a nicely colored bundle of points, with the hue of each one based on its distance from the origin, as shown here:

Hence, we see here that it is quite easy to generate 3D plots in Matplotlib. In the past, generating 3D plots required jumping through a lot of hoops, and often it was easier to use other tools, but the 3D plotting infrastructure within Matplotlib has actually matured quite a bit in the past few years.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset