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 can I convert numbers to a color scale in Matplotlib?
To convert numbers to a color scale in Matplotlib, you can map numerical values to colors using colormaps and normalization. This technique is commonly used in scatter plots, heatmaps, and other visualizations where color represents data magnitude.
Basic Color Mapping with Scatter Plot
Here's how to create a scatter plot where colors represent numerical values ?
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Create sample data
x = np.arange(12)
y = np.random.rand(len(x)) * 20
c = np.random.rand(len(x)) * 3 + 1.5
# Create DataFrame
df = pd.DataFrame({"x": x, "y": y, "c": c})
# Create the plot
fig, ax = plt.subplots(figsize=(8, 4))
# Create scatter plot with color mapping
scatter = ax.scatter(df.x, df.y, c=df.c, cmap='hot', s=100)
# Add colorbar
plt.colorbar(scatter, label='Color Value')
# Customize the plot
ax.set_xlabel('X Values')
ax.set_ylabel('Y Values')
ax.set_title('Numbers to Color Scale Example')
ax.set_xticks(df.x)
plt.tight_layout()
plt.show()
Using Normalize for Custom Color Range
When you want to control the color mapping range, use the Normalize class ?
from matplotlib import pyplot as plt, colors
import numpy as np
# Sample data
values = np.array([1.2, 2.5, 3.8, 4.1, 4.9, 2.1, 3.3, 1.8, 4.5, 3.0])
x_pos = np.arange(len(values))
y_pos = np.ones(len(values))
# Create normalization (maps values to 0-1 range)
norm = colors.Normalize(vmin=1.0, vmax=5.0)
cmap = plt.cm.viridis
# Create the plot
fig, ax = plt.subplots(figsize=(10, 3))
# Plot with normalized colors
scatter = ax.scatter(x_pos, y_pos, c=values, cmap=cmap, norm=norm, s=200)
# Add colorbar with the same normalization
cbar = plt.colorbar(scatter)
cbar.set_label('Normalized Values', rotation=270, labelpad=20)
# Customize plot
ax.set_ylim(0.5, 1.5)
ax.set_xlabel('Data Points')
ax.set_title('Custom Color Range with Normalize')
plt.show()
Different Colormaps
Matplotlib offers various colormaps for different visualization needs ?
import matplotlib.pyplot as plt
import numpy as np
# Generate sample data
data = np.random.randn(50) * 2 + 5
x = np.arange(len(data))
y = np.random.randn(len(data)) * 0.5
# Different colormaps to demonstrate
cmaps = ['viridis', 'plasma', 'hot', 'coolwarm']
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
axes = axes.flatten()
for i, cmap_name in enumerate(cmaps):
scatter = axes[i].scatter(x, y, c=data, cmap=cmap_name, alpha=0.7)
axes[i].set_title(f'Colormap: {cmap_name}')
plt.colorbar(scatter, ax=axes[i])
plt.tight_layout()
plt.show()
Key Parameters
| Parameter | Description | Example |
|---|---|---|
c |
Color values (numbers) | c=data_array |
cmap |
Colormap name | cmap='viridis' |
norm |
Normalization object | norm=colors.Normalize(0, 10) |
vmin/vmax |
Color scale limits | vmin=0, vmax=100 |
Conclusion
Converting numbers to color scales in Matplotlib involves using the c parameter with colormaps and optional normalization. Use scatter() with cmap for basic mapping, and Normalize() for custom color ranges.
Advertisements
