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
3D scatterplots in Python Matplotlib with hue colormap and legend
3D scatter plots with hue colormaps allow you to visualize four dimensions of data simultaneously: x, y, z coordinates and a color dimension. In this tutorial, we'll create 3D scatter plots using Matplotlib with Seaborn color palettes and legends.
Basic 3D Scatter Plot with Hue Colormap
Let's create a 3D scatter plot where points are colored based on their x-coordinate values ?
import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt
from matplotlib.colors import ListedColormap
# Set figure size
plt.rcParams["figure.figsize"] = [8.00, 6.00]
plt.rcParams["figure.autolayout"] = True
# Generate random data points
x = np.random.rand(100)
y = np.random.rand(100)
z = np.random.rand(100)
# Create 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Create colormap using Seaborn's husl palette
cmap = ListedColormap(sns.color_palette("husl", 256).as_hex())
# Create scatter plot with color based on x values
sc = ax.scatter(x, y, z, s=40, c=x, marker='o', cmap=cmap, alpha=0.8)
# Add colorbar legend
plt.colorbar(sc, ax=ax, shrink=0.5, aspect=10)
# Set labels
ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis')
ax.set_zlabel('Z Axis')
ax.set_title('3D Scatter Plot with Hue Colormap')
plt.show()
Using Different Color Variables
You can color points based on any variable, not just coordinates. Here's an example using a calculated distance from origin ?
import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt
from matplotlib.colors import ListedColormap
# Generate data
np.random.seed(42)
x = np.random.rand(150) * 10
y = np.random.rand(150) * 10
z = np.random.rand(150) * 10
# Calculate distance from origin as color variable
distances = np.sqrt(x**2 + y**2 + z**2)
# Create 3D plot
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
# Use viridis colormap
sc = ax.scatter(x, y, z, s=50, c=distances, marker='o', cmap='viridis', alpha=0.7)
# Add colorbar with label
cbar = plt.colorbar(sc, ax=ax, shrink=0.6, aspect=15)
cbar.set_label('Distance from Origin', rotation=270, labelpad=20)
# Customize plot
ax.set_xlabel('X Coordinate')
ax.set_ylabel('Y Coordinate')
ax.set_zlabel('Z Coordinate')
ax.set_title('3D Scatter Plot Colored by Distance')
plt.show()
Categorical Color Mapping with Legend
For categorical data, you can create discrete color groups with a custom legend ?
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
# Generate data
np.random.seed(123)
n_points = 120
x = np.random.randn(n_points)
y = np.random.randn(n_points)
z = np.random.randn(n_points)
# Create categorical groups
categories = np.random.choice(['Group A', 'Group B', 'Group C'], n_points)
category_codes = np.array([0 if cat == 'Group A' else 1 if cat == 'Group B' else 2 for cat in categories])
# Create custom colormap
colors = ['red', 'green', 'blue']
cmap = ListedColormap(colors)
# Create 3D plot
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
# Scatter plot with categorical colors
sc = ax.scatter(x, y, z, s=60, c=category_codes, cmap=cmap, alpha=0.8)
# Create custom legend
handles = [plt.scatter([], [], c=colors[i], s=60, label=f'Group {chr(65+i)}')
for i in range(3)]
ax.legend(handles=handles, loc='upper right')
# Labels and title
ax.set_xlabel('X Values')
ax.set_ylabel('Y Values')
ax.set_zlabel('Z Values')
ax.set_title('3D Scatter Plot with Categorical Colors')
plt.show()
Key Parameters
| Parameter | Description | Example Values |
|---|---|---|
c |
Color variable or array | x, y, distances, categories |
cmap |
Colormap name or object | 'viridis', 'plasma', ListedColormap |
s |
Point size | 20, 50, 100 |
alpha |
Transparency level | 0.5, 0.8, 1.0 |
Conclusion
3D scatter plots with hue colormaps effectively visualize multi-dimensional data by mapping colors to data values. Use colorbar() for continuous variables and custom legends for categorical data to make your plots informative and visually appealing.
