82 views
3D Scatter Plotting in Python using Matplotlib
Creating a 3D scatter plot in Python using Matplotlib is a great way to visualize three-dimensional data. Here’s an example of how to create a basic 3D scatter plot:
Python
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
# Generate some random 3D data
np.random.seed(42)
num_points = 100
x = np.random.rand(num_points)
y = np.random.rand(num_points)
z = np.random.rand(num_points)
# Create a 3D figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Create the 3D scatter plot
ax.scatter(x, y, z, c='b', marker='o')
# Set labels for the axes
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
# Set a title for the plot
plt.title('3D Scatter Plot Example')
# Show the plot
plt.show()
In this example:
- We import Matplotlib’s
pyplot
module and theAxes3D
module frommpl_toolkits.mplot3d
. - We generate some random 3D data for the x, y, and z coordinates. You can replace this with your own data.
- We create a 3D figure using
plt.figure()
and add a subplot with 3D projection usingfig.add_subplot(111, projection='3d')
. - We create the 3D scatter plot using
ax.scatter()
, specifying the x, y, and z coordinates. Thec
argument sets the color, and themarker
argument sets the marker style. - We set labels for the x, y, and z axes using
ax.set_xlabel()
,ax.set_ylabel()
, andax.set_zlabel()
. - We set a title for the plot using
plt.title()
. - Finally, we display the 3D scatter plot using
plt.show()
.
This code will create a 3D scatter plot with random data. You can customize the data and appearance of the plot to suit your specific requirements.