3D Plots - ( Advanced Plotting Techniques )
Heading h2
Syntax
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(xs, ys, zs, c=c, marker=m)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()
Example
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# generate random data points
x = np.random.randn(100)
y = np.random.randn(100)
z = np.random.randn(100)
# create 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z, c='r', marker='o')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()
Output
A 3D scatter plot is displayed with the randomly generated data points in red color and circular markers.
Explanation
3D plots are a powerful way to visualize data when you have three variables involved. The matplotlib
library in Python provides the Axes3D
class that can be used to create 3D plots.
To generate a 3D plot, you first need to create a figure object and then create a Axes3D
object to plot on. Once the Axes3D
object is created, you can use the scatter()
method to add data points to the plot. The set_xlabel()
, set_ylabel()
, and set_zlabel()
methods can be used to name the x, y, and z-axis respectively.
In the above example, we generate a set of random data points and use the scatter()
method to plot them in a 3D space. We set the color and marker style of the data points using the c
and marker
arguments respectively. Finally, we label the x, y, and z-axis using the set_xlabel()
, set_ylabel()
, and set_zlabel()
methods.
Use
3D plots can be used to visualize complex data with three variables involved. They are useful in various scientific and engineering applications where you need to analyze how three different variables are related to each other.
Important Points
mpl_toolkits.mplot3d
module provides theAxes3D
class for 3D plots inmatplotlib
.scatter()
method can be used to add data points to the 3D plot.set_xlabel()
,set_ylabel()
, andset_zlabel()
methods can be used to label the x, y, and z-axis respectively.
Summary
In conclusion, 3D plots are a powerful way to visualize data involving three variables. The matplotlib
library in Python provides the Axes3D
class that can be used to create 3D plots. scatter()
method is used to add data points to the 3D plot, and set_xlabel()
, set_ylabel()
, and set_zlabel()
methods are used to label the x, y, and z-axis respectively.