Colormaps
DS 2023 | Communicating with Data

Overview¶
In Matplotlib, a colormap is used to map scalar data values to color values.
Colors are used to replace numbers in a visualization to display quantitive meaning.
Data are usually normalized to a scale between 0 and 1 and then mapped onto colors represented using the RGBA encoding scheme.
Use cases¶
Colormaps are used everywhere in visualization.
Nearly every plot type in Matplotlib has a paramter to define color.
Colormaps are especially useful for visualizing 2D or 3D data arrays in plots like heatmaps, surface plots, scatter plots, and contour maps.
Representing color as RGBA¶
RGBA is a color encoding scheme that defines a color in terms of four channels: Red, Green, Blue, and Alpha.
Each color channel may have a value between 0 and 255, yielding 2563 or colors.
In this way, every color is defined as a mixture of red, green, and blue.
The alpha channel determines the opacity of a color, ranging from 0.0 to 1.0.
Color codes and names¶
Here is a table featuring showing some common colors and their codes:
| Color Name | Decimal Value (R, G, B) | Hex Code | Swatch |
|---|---|---|---|
| Red | 255, 0, 0 | #FF0000 | ██ |
| Green | 0, 255, 0 | #00FF00 | ██ |
| Blue | 0, 0, 255 | #0000FF | ██ |
| Yellow | 255, 255, 0 | #FFFF00 | ██ |
| Cyan | 0, 255, 255 | #00FFFF | ██ |
| Magenta | 255, 0, 255 | #FF00FF | ██ |
| Orange | 255, 165, 0 | #FFA500 | ██ |
| Purple | 128, 0, 128 | #800080 | ██ |
| White | 255, 255, 255 | #FFFFFF | ██ |
| Black | 0, 0, 0 | #000000 | ██ |
Palettes and their uses¶
Matplotlib comes with a number of colormaps to choose from.
These are grouped into five primary classes based on their mathematical structures and how human eyes perceive them.
Perceptually Uniform¶
General scientific data, accurate perception.
Lightness increases monotonically; converts flawlessly to grayscale.

Sequential¶
Ordered data moving from low to high values.
Smooth variation between two color tones (e.g., low saturation to high saturation).

Diverging¶
Data with a critical midpoint or zero value.
Two divergent hues that meet at an unsaturated, neutral middle color.

Cyclic¶
Wrapping values or periodic data.
Start and end colors match smoothly; ideal for phase angles, wind directions, or hourly time.

Qualitative¶
Unordered or categorical classes, as with nominal grouping data.
Distinct, miscellaneous hues with non-monotonic lightness to distinguish discrete sets.

Matplotlib’s colormap object¶
Sometimes it is necessary to access a colormap object, as opposed to just passing its name to the cmap argument of a plotting function.
To do this, you can use PyPlot’s colormaps object.
Here we call the object and show all the colormap names it has.
import matplotlib.pyplot as plt
import matplotlib as mpl
from IPython.display import HTML
HTML(" ".join([f"<span style='font-family:monospace;font-weight:bold;'>{cmap_name}</span>" for cmap_name in plt.colormaps]))Let’s look at one:
my_cmap = plt.colormaps['viridis']
print(my_cmap.N)
my_cmap256
You can pass a scaled number to the object to get its RGBA values.
my_cmap(.5)(np.float64(0.127568),
np.float64(0.566949),
np.float64(0.550556),
np.float64(1.0))You can also pass it a number between 0 and , the number of values in the colormap.
You can get the number of values in the colormap by appending .N to the object, like so:
my_cmap.N256And here we acces the color at 233.
my_cmap(233)(np.float64(0.772852),
np.float64(0.877868),
np.float64(0.131109),
np.float64(1.0))The return value can be converted to a code suitable for using in HTML.
mpl.colors.to_hex(my_cmap(.5))'#21918c'Here is an example of this code being used to color some text.
<span style="color:#21918c;font-size:64px;">██ Here is an example.</span>██ Here is an example.
Putting colormaps to work¶
Let’s put the colormap to work.
In the bad old days, Pandas’ scatter plot function did not allow you to pass a variable name to the c argument.
To get that effect, you had to do it by hand.
Tedious as it was, it illustrated how colormaps can be used.
This is useful knowledge in other contexts.
Let’s look at an example.
Let’s create a scatter plot of two variables from the iris dataset and color them by species.
import seaborn as sns
import pandas as pd
iris = sns.load_dataset('iris')
iris.head()To this, we first generate a number to go with each member of the species domain.
If the variable is cast as a Categorical data type, this is easy: we just grab the codes associated with the elements (levels) of the category.
iris['species'] = pd.Categorical(iris['species'])
iris.species.cat.codes0 0
1 0
2 0
3 0
4 0
..
145 2
146 2
147 2
148 2
149 2
Length: 150, dtype: int8Now all we do is pass the series of codes to the c argument.
We also specify a colormap with cmap.
Here we choose on from the qualitative group.
iris.plot.scatter(
x='sepal_length',
y='petal_width',
c=iris.species.cat.codes,
cmap='Set1')
plt.show()
The result is not ideal because the colorback represents the number as a continuous variable, and does not show the relationship between color and category.
To get the proper result, we turn off the colorbar and add a legend.
ax = iris.plot.scatter(
x='sepal_length',
y='petal_width',
c=iris.species.cat.codes,
cmap='Set1',
colorbar=False # Turn off the colorbar
)
# Add a legend
ax.legend(
handles=ax.collections[0].legend_elements()[0],
labels=list(iris['species'].cat.categories),
title="Species"
)
plt.show()
Again, this is tedious, but you can see how colormaps are used.
They take a numeric represenation of variable and return a color that can be used for visualization.
Color names¶
Finally, here are some of the color names available to use in Matplotlib whenever you are asked to define a color for some visual feature.
For example, you may want to define the color of a line as magenta.
Matplotlib comes with a few libraries of colors:
BASE_COLORS
CSS4_COLORS
TABLEAU_COLORS
XKCD_COLORS
The names and their color values are available as dictionaries from the mpl.colors object.
For example:
mpl.colors.BASE_COLORS{'b': (0, 0, 1),
'g': (0, 0.5, 0),
'r': (1, 0, 0),
'c': (0, 0.75, 0.75),
'm': (0.75, 0, 0.75),
'y': (0.75, 0.75, 0),
'k': (0, 0, 0),
'w': (1, 1, 1)}mpl.colors.TABLEAU_COLORS{'tab:blue': '#1f77b4',
'tab:orange': '#ff7f0e',
'tab:green': '#2ca02c',
'tab:red': '#d62728',
'tab:purple': '#9467bd',
'tab:brown': '#8c564b',
'tab:pink': '#e377c2',
'tab:gray': '#7f7f7f',
'tab:olive': '#bcbd22',
'tab:cyan': '#17becf'}Let’s create a function to display a color given its name.
import matplotlib.patches as patches
def plot_swatch(color_name):
fig, ax = plt.subplots(figsize=(2, 2))
swatch = patches.Rectangle((0, 0), 1, 1, facecolor=color_name)
ax.add_patch(swatch)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.axis('off')
ax.set_title(color_name)
plt.show()plot_swatch('tab:orange')
Here is a function to show all the colors in a collection.
def print_colors(mpl_library, w=8):
N = len(mpl_library)
h = N // w + int(bool(N % w))
fig, ax = plt.subplots(h, w, figsize=(w, h*1.1), subplot_kw={'xticks': [], 'yticks': []})
for i, color_name in enumerate(mpl_library):
c = i % w
r = i // w
swatch = patches.Rectangle((0, 0), 1, 1, facecolor=color_name)
ax[r,c].add_patch(swatch)
ax[r,c].set_title(color_name.replace(":",":\n"), fontsize=8)
sns.despine(left=True, bottom=True)
plt.tight_layout()
plt.show()
print_colors(mpl.colors.BASE_COLORS, w=4)
print_colors(mpl.colors.TABLEAU_COLORS, w=5)
print_colors(mpl.colors.CSS4_COLORS)
The XKCD_COLORS dictionary has too many values to print, so we show a sample from it instead.
xkcd = pd.Series(mpl.colors.XKCD_COLORS)
print(len(xkcd))949
print_colors(xkcd.sample(64).to_dict())