Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to plot scatter points in a 3D figure with a colorbar in Matplotlib?
To create 3D scatter plots with colorbars in Matplotlib, we use the scatter() method on a 3D axes object along with colorbar() to display a color scale. The colorbar helps visualize how point colors relate to data values.
Basic 3D Scatter Plot with Colorbar
Here's how to create a 3D scatter plot where point colors are mapped to one of the coordinate values ?
import numpy as np
import matplotlib.pyplot as plt
# Set figure size
plt.rcParams["figure.figsize"] = [10, 8]
plt.rcParams["figure.autolayout"] = True
# Create figure and 3D axis
fig = plt.figure()
ax = fig.add_subplot(projection="3d")
# Generate random data points
xs = np.random.rand(100)
ys = np.random.rand(100)
zs = np.random.rand(100)
# Create scatter plot with colors based on x-values
scatter = ax.scatter(xs, ys, zs, c=xs, cmap="viridis", s=50)
# Add colorbar
plt.colorbar(scatter, ax=ax, shrink=0.8)
# Set labels
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
ax.set_title('3D Scatter Plot with Colorbar')
plt.show()
Using Different Color Mappings
You can map colors to any data values, not just coordinates ?
import numpy as np
import matplotlib.pyplot as plt
# Create figure
fig = plt.figure(figsize=(12, 5))
# First subplot: Color by distance from origin
ax1 = fig.add_subplot(121, projection="3d")
xs = np.random.rand(100) * 2 - 1
ys = np.random.rand(100) * 2 - 1
zs = np.random.rand(100) * 2 - 1
# Calculate distance from origin
distances = np.sqrt(xs**2 + ys**2 + zs**2)
scatter1 = ax1.scatter(xs, ys, zs, c=distances, cmap="plasma", s=60)
plt.colorbar(scatter1, ax=ax1, shrink=0.8)
ax1.set_title('Color by Distance from Origin')
# Second subplot: Color by sum of coordinates
ax2 = fig.add_subplot(122, projection="3d")
coord_sum = xs + ys + zs
scatter2 = ax2.scatter(xs, ys, zs, c=coord_sum, cmap="coolwarm", s=60)
plt.colorbar(scatter2, ax=ax2, shrink=0.8)
ax2.set_title('Color by Sum of Coordinates')
plt.tight_layout()
plt.show()
Customizing the Colorbar
You can customize colorbar appearance, including position, size, and labels ?
import numpy as np
import matplotlib.pyplot as plt
# Generate sample data
np.random.seed(42)
n_points = 150
xs = np.random.normal(0, 1, n_points)
ys = np.random.normal(0, 1, n_points)
zs = np.random.normal(0, 1, n_points)
# Create temperature-like values
temperatures = 20 + 10 * np.sin(xs) + 5 * np.cos(ys) + 2 * zs
# Create plot
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(projection="3d")
scatter = ax.scatter(xs, ys, zs, c=temperatures,
cmap="coolwarm", s=80, alpha=0.8)
# Customize colorbar
cbar = plt.colorbar(scatter, ax=ax, shrink=0.6, pad=0.1)
cbar.set_label('Temperature (°C)', rotation=270, labelpad=20)
cbar.ax.tick_params(labelsize=10)
# Set plot properties
ax.set_xlabel('X Position')
ax.set_ylabel('Y Position')
ax.set_zlabel('Z Position')
ax.set_title('3D Temperature Visualization', fontsize=14)
plt.show()
Key Parameters
| Parameter | Description | Example Values |
|---|---|---|
c |
Color values for points | Array of numbers |
cmap |
Colormap name | "viridis", "plasma", "coolwarm" |
s |
Point size | 20, 50, 100 |
shrink |
Colorbar size factor | 0.5, 0.8, 1.0 |
Conclusion
Use ax.scatter() with the c parameter to map colors to data values, then add plt.colorbar() for the color scale. Customize the colorbar with shrink, pad, and label parameters for better visualization.
Advertisements
