How to convert data values into color information for Matplotlib?

Converting data values into color information for Matplotlib allows you to create visually appealing scatter plots where colors represent data patterns. This process involves using colormaps to map numerical values to specific colors.

Basic Color Mapping with Colormaps

The most straightforward approach uses Matplotlib's built-in colormaps to automatically map data values to colors ?

import numpy as np
import matplotlib.pyplot as plt

# Set figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# Create sample data
values = np.random.rand(100)
x = np.random.rand(len(values))
y = np.random.rand(len(values))

# Create scatter plot with automatic color mapping
sc = plt.scatter(x, y, c=values, cmap='viridis')
plt.colorbar(sc, label='Data Values')
plt.title('Automatic Color Mapping')
plt.show()

Manual Color Mapping Using get_cmap()

For more control, you can manually convert values using a colormap instance ?

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# Get colormap instance
plasma = plt.get_cmap('GnBu_r')
values = np.random.rand(100)

# Create random data points
x = np.random.rand(len(values))
y = np.random.rand(len(values))

# Manually map values to colors
colors = [plasma(val) for val in values]
sc = plt.scatter(x, y, c=colors)
plt.title('Manual Color Mapping with get_cmap()')
plt.show()

Normalizing Data for Better Color Mapping

When your data has a wide range, normalizing helps create better color contrast ?

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize

# Create data with wide range
data_values = np.random.uniform(10, 1000, 50)
x = np.random.rand(len(data_values))
y = np.random.rand(len(data_values))

# Normalize data to 0-1 range
norm = Normalize(vmin=data_values.min(), vmax=data_values.max())
normalized_values = norm(data_values)

# Apply colormap
cmap = plt.get_cmap('plasma')
colors = cmap(normalized_values)

plt.scatter(x, y, c=colors, s=50)
plt.colorbar(plt.cm.ScalarMappable(norm=norm, cmap=cmap), label='Original Values')
plt.title('Normalized Color Mapping')
plt.show()

Popular Colormaps for Data Visualization

Colormap Type Best For
viridis Sequential Continuous data, perceptually uniform
plasma Sequential Heat maps, intensity data
coolwarm Diverging Data with positive/negative values
tab10 Qualitative Categorical data, distinct groups

Conclusion

Use c=values with cmap parameter for automatic color mapping. For manual control, use get_cmap() to convert values to colors. Always consider normalizing your data for better visual contrast.

Updated on: 2026-03-25T21:38:43+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements