matplotlib
color map
Python
data visualization
tutorial

Getting individual colors from a color map in matplotlib

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

A Matplotlib colormap is just a callable object that maps a normalized number to an RGBA color. Once you understand that, getting individual colors is straightforward: choose a colormap, pass in one or more values between 0 and 1, and optionally convert the resulting RGBA tuples to hex strings for reuse.

The Basic API

In current Matplotlib versions, the modern way to access a colormap is through matplotlib.colormaps.

python
1import matplotlib as mpl
2
3cmap = mpl.colormaps["viridis"]
4color = cmap(0.25)
5print(color)

The result is an RGBA tuple with values in the 0 to 1 range, for example red, green, blue, and alpha.

A value near 0 samples the start of the colormap. A value near 1 samples the end.

Sampling Several Colors Evenly

A common use case is taking n evenly spaced colors from a continuous colormap for multiple lines or categories.

python
1import numpy as np
2import matplotlib as mpl
3
4cmap = mpl.colormaps["plasma"]
5positions = np.linspace(0, 1, 5)
6colors = [cmap(p) for p in positions]
7
8for c in colors:
9    print(c)

This is useful when you want visually related colors instead of Matplotlib’s default cycle.

If you use many categories, a continuous colormap sampled this way usually looks cleaner than manually choosing unrelated hex codes.

Converting to Hex Colors

Sometimes you want to reuse the sampled colors in annotations, style dictionaries, or other plotting libraries. Convert RGBA values to hex with matplotlib.colors.to_hex.

python
1import numpy as np
2import matplotlib as mpl
3from matplotlib.colors import to_hex
4
5cmap = mpl.colormaps["viridis"]
6hex_colors = [to_hex(cmap(p)) for p in np.linspace(0, 1, 4)]
7print(hex_colors)

That produces strings like #440154, which are convenient when you need a stable textual color representation.

Using a Normalizer with Real Data

The most useful mental model is that colormaps expect normalized values. If your real data is in a different range, use a normalizer first.

python
1import matplotlib as mpl
2
3values = [10, 20, 35, 50]
4norm = mpl.colors.Normalize(vmin=min(values), vmax=max(values))
5cmap = mpl.colormaps["cividis"]
6
7for value in values:
8    print(value, cmap(norm(value)))

This is the same logic Matplotlib uses internally for scatter plots, heatmaps, and other scalar-mapped visuals. Doing it explicitly is helpful when you want consistent colors across multiple charts.

Continuous Versus Discrete Colormaps

Not every colormap should be sampled the same way. Continuous colormaps such as viridis, plasma, and cividis are good for scalar gradients. Qualitative colormaps such as tab10 or Set2 are better for categories.

If you only need a handful of distinct category colors, sampling a qualitative colormap is often better than taking equally spaced values from a gradient. That avoids visually ambiguous neighboring shades.

python
1import matplotlib as mpl
2
3cmap = mpl.colormaps["tab10"]
4for i in range(5):
5    print(i, cmap(i))

For a listed qualitative map, integer-like indexing through the colormap object is often the simplest pattern.

A Small Plot Example

python
1import numpy as np
2import matplotlib.pyplot as plt
3import matplotlib as mpl
4
5x = np.linspace(0, 2 * np.pi, 200)
6cmap = mpl.colormaps["viridis"]
7
8for idx, p in enumerate(np.linspace(0.2, 0.8, 4)):
9    plt.plot(x, np.sin(x + idx * 0.4), color=cmap(p), label=f"line {idx}")
10
11plt.legend()
12plt.show()

This gives a coordinated set of four distinct line colors sampled from the same palette.

Common Pitfalls

A common mistake is passing raw data values directly into the colormap without normalizing them first. Colormaps expect values in the 0 to 1 interval unless you intentionally rely on clipping behavior.

Another mistake is using a sequential colormap for purely categorical labels. The colors may look related, but categories become harder to distinguish.

A third issue is using the older cm.get_cmap style blindly from older examples without realizing the modern registry API is now preferred.

Summary

  • A Matplotlib colormap is a callable that returns RGBA colors.
  • Use matplotlib.colormaps[name] to get the colormap in current Matplotlib.
  • Sample one color with a single normalized value or many colors with np.linspace.
  • Use Normalize when mapping real data ranges to colors.
  • Convert RGBA results to hex when you need reusable text color codes.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design