0
0
Matplotlibdata~5 mins

3D scatter plots in Matplotlib

Choose your learning style9 modes available
Introduction

3D scatter plots help you see how three different things relate to each other in space. They make it easier to understand patterns when data has three parts.

When you want to explore how three measurements of something connect, like height, weight, and age.
When you want to find groups or clusters in data with three features.
When you want to show data points in a way that looks like a 3D cloud.
When you want to compare three variables visually to find trends or outliers.
Syntax
Matplotlib
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z, c=color, marker=marker)
plt.show()

Use projection='3d' to create a 3D plot.

x, y, and z are lists or arrays of numbers representing points in 3D space.

Examples
Simple 3D scatter plot with three points.
Matplotlib
ax.scatter([1, 2, 3], [4, 5, 6], [7, 8, 9])
Scatter plot with red triangle markers.
Matplotlib
ax.scatter(x, y, z, c='red', marker='^')
Scatter plot with colors for each point.
Matplotlib
ax.scatter(x, y, z, c=colors, marker='o')
Sample Program

This program creates 50 random points in 3D space. Each point has a color from a color map. The plot shows these points with a color bar to explain the colors.

Matplotlib
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

# Create data
np.random.seed(0)
x = np.random.rand(50)
y = np.random.rand(50)
z = np.random.rand(50)
colors = np.random.rand(50)

# Create figure and 3D axis
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Plot 3D scatter
scatter = ax.scatter(x, y, z, c=colors, cmap='viridis', marker='o')

# Add color bar
fig.colorbar(scatter, ax=ax, label='Color scale')

# Set labels
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')

plt.show()
OutputSuccess
Important Notes

You can change marker shapes with the marker parameter, like 'o' for circles or '^' for triangles.

Use cmap to apply color maps for better color visualization.

Remember to label axes so others understand what each axis means.

Summary

3D scatter plots show points in three dimensions to help see relationships.

Use projection='3d' to create 3D plots in matplotlib.

Colors and markers can make your plot clearer and more informative.