In Chapter 6, Hello Plotting World!, we have already explored scatter plots in two dimensions. In this section, let's try to create a 3D scatter plot. Before doing that, we need some data points in three dimensions (x, y, z):
import pandas as pd
source = "https://raw.githubusercontent.com/PointCloudLibrary/data/master/tutorials/ism_train_cat.pcd"
cat_df = pd.read_csv(source, skiprows=11, delimiter=" ", names=["x","y","z"], encoding='latin_1')
cat_df.head()
Point | x | y | z |
0 | -17.034178 | 18.972282 | 40.482403 |
1 | -16.881481 | 21.815451 | 44.156799 |
2 | -16.749582 | 18.154911 | 34.131474 |
3 | -16.876919 | 20.598286 | 36.271809 |
4 | -16.849340 | 17.403711 | 42.993984 |
To declare a 3D plot, we first need to import the Axes3D object from the mplot3d extension in mpl_toolkits, which is responsible for rendering 3D plots in a 2D plane. After that, we need to specify projection='3d' when we create subplots:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(cat_df.x, cat_df.y, cat_df.z)
plt.show()
Behold, the mighty sCATter plot in 3D. Cats are currently taking over the internet. According to the New York Times, cats are "the essential building block of the Internet" (https://www.nytimes.com/2014/07/23/upshot/what-the-internet-can-see-from-your-cat-pictures.html). Undoubtedly, they deserve a place in this chapter as well.
Contrary to the 2D version of scatter(), we need to provide X, Y, and Z coordinates when we are creating a 3D scatter plot. Yet the parameters that are supported in 2D scatter() can be applied to 3D scatter() as well:
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Change the size, shape and color of markers
ax.scatter(cat_df.x, cat_df.y, cat_df.z, s=4, c="g", marker="o")
plt.show()
To change the viewing angle and elevation of the 3D plot, we can make use of view_init(). The azim parameter specifies the azimuth angle in the X-Y plane, while elev specifies the elevation angle. When the azimuth angle is 0, the X-Y plane would appear to the north from you. Meanwhile, an azimuth angle of 180 would show you the south side of the X-Y plane:
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(cat_df.x, cat_df.y, cat_df.z,s=4, c="g", marker="o")
# elev stores the elevation angle in the z plane azim stores the
# azimuth angle in the x,y plane
ax.view_init(azim=180, elev=10)
plt.show()