HOWTO · Matplotlib
How to Custom Colormap Using Python Matplotlib
Create discrete and continuous custom colormaps with Matplotlib in Python, inspect built-in colors, and apply each map to plotted data.
On this page
Use ListedColormap when each category needs a distinct color, and LinearSegmentedColormap when values should transition through a gradient. Both are Matplotlib colormap classes and can be passed to plotting functions through the cmap argument. This guide also shows how to inspect a built-in map and retrieve its RGBA values.
Use Matplotlib to Create a Custom Colormap in Python
A colormap maps numeric values to colors. For category codes or a small set of fixed colors, define a ListedColormap. For measurements whose colors should blend smoothly, define a LinearSegmentedColormap. When applying either map, use a normalization that matches the range of the values being colored; otherwise the plotted colors may not represent the intended data range.
Use Matplotlib’s get_cmap() Function to Access Colormaps and Their Values in Python
The get_cmap() function retrieves a named built-in map. A colormap is callable: pass a value from 0 to 1 to retrieve an RGBA tuple, where the final component is opacity. To inspect sampled colors, pass a sequence of values instead. This example prints one sampled color:
import matplotlib.pyplot as plt
viridis = plt.get_cmap("viridis")
print(viridis(0.56))
(np.float64(0.120081), np.float64(0.622161), np.float64(0.534946), np.float64(1.0))
For a finite lookup table, resample the map with viridis.resampled(8). A ListedColormap exposes its entries through colors; a continuous map such as LinearSegmentedColormap is sampled by calling it with values.
Use the colors Attribute of ListedColormap to Create a Custom Listed Colormap in Python
ListedColormap accepts color names or numeric RGBA entries. RGBA channel values are conventionally in the range 0 to 1. Its colors attribute contains the discrete entries when the map is represented as a list. The following standalone example builds both forms and applies the named-color map to category codes in a scatter plot. Adapt categories and the normalization to match your data.
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap, Normalize
named_map = ListedColormap(["darkorange", "gold", "lightseagreen"], name="groups")
rgba_map = ListedColormap([
(0.58, 0.41, 0.27, 1.0),
(0.00, 0.41, 0.27, 1.0),
(0.58, 0.00, 0.27, 1.0),
], name="rgba_groups")
x = [1, 2, 3, 4, 5, 6]
y = [1, 4, 2, 5, 3, 6]
categories = [0, 0, 1, 1, 2, 2]
plt.scatter(x, y, c=categories, cmap=named_map, norm=Normalize(0, 2))
plt.colorbar(ticks=[0, 1, 2])
plt.show()
The Normalize(0, 2) call maps the category codes across the three entries, and the colorbar ticks identify those codes. Use rgba_map.colors to inspect the explicit RGBA list. If the number of colors and category codes differ, adjust the map or normalization so each category is assigned as intended.
How to Create a Custom Linear Segmented Colormap in Python?
A LinearSegmentedColormap interpolates color channels between specified positions to create a gradient. Its cdict (color dictionary) has channel keys such as red, green, and blue. Each channel’s rows have the form [x, yleft, yright]: x is a position from 0 to 1, and the other values give the channel level on either side of that position. Keep the positions increasing from 0 to 1. Equal left and right values make a continuous transition at an anchor; different values describe a jump.
This standalone example creates an anchor-point gradient and a second gradient with from_list(), then displays each on sample data. The rendered figures were not visually checked.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LinearSegmentedColormap
cdict = {
"red": [(0.0, 0.0, 0.0), (0.5, 0.1, 0.1), (1.0, 1.0, 1.0)],
"green": [(0.0, 0.0, 0.0), (0.5, 0.8, 0.8), (1.0, 0.2, 0.2)],
"blue": [(0.0, 0.4, 0.4), (0.5, 0.1, 0.1), (1.0, 0.0, 0.0)],
}
anchor_map = LinearSegmentedColormap("anchor_gradient", cdict, N=256)
list_map = LinearSegmentedColormap.from_list(
"list_gradient", ["navy", "gold", "crimson"], N=256
)
values = np.arange(36).reshape(6, 6)
fig, axes = plt.subplots(1, 2)
for ax, cmap, title in zip(axes, [anchor_map, list_map], ["Anchors", "Color list"]):
image = ax.imshow(values, cmap=cmap)
ax.set_title(title)
fig.colorbar(image, ax=ax)
plt.tight_layout()
plt.show()
Use the dictionary constructor when channel-level control or explicit anchors matter. Use LinearSegmentedColormap.from_list() for a straightforward gradient through named colors; the colors are interpolated across the map. N sets the lookup-table size, and gamma controls scaling of the input positions.
Conclusion
Choose ListedColormap for discrete categories with deliberate color assignments. Choose LinearSegmentedColormap for a continuous gradient, using either cdict anchor points or from_list() colors. Retrieve built-in maps with get_cmap(), inspect their sampled RGBA values, and pass the chosen map with an appropriate normalization to the plot.