part of Course 133 Navigating Matplotlib



Choosing a color

You don't need to be bound to Matplotlib's default color palette. You can customize the color for every element you draw. There are several ways to specify colors, and covering all of them deserves its own tutorial, but the simplest way is to call out the (English) name of a color. Matplotlib can recognize a shocking variety of them. Here are some samples. They include the named CSS colors.

named CSS colors

There is also a dazzling collection of 954 colors curated by xkcd, including "kermit green" and "heliotrope". Keep in mind that whenever you want to use one of these you'll have to call it by its full name — "xkcd:kermit green" or "xkcd:heliotrope".

named colors from xkcd survey

And if you find it helpful, you can also use a color's hex string. (Here's a deeper dive on the topic if you're interested.) If your monitor can show it, you can draw with it in Matplotlib.

Choosing colors

Choosing the right color combination for your project is a special skill, and not one I feel confident in. I'm convinced that visual designers are wizards. Wherever your own color perception skills are, there are a couple of tools that will help you level up. Colorizer.org has a slick set of sliders you can adjust to choose the right color combo in any one of several color spaces. And if you'd like a primer to color selection and design, this post by Lisa Charlotte Rost is shockingly accessible.

Colormaps

When creating an image from a single channel (a two-dimensional array), Matplotlib gives you lots of different options for how to color it.

matplotlib colormaps

To choose your color scheme, pass the colormap by name to imshow(), like this:

ax.imshow(image, cmap="inferno")

Create a custom colormap

Matplotlib also gives you complete control in creating your own colormaps. There are several ways to go about it, but my favorite is this: make a list of colors you'd like the colormap to hit, and let LinearSegmentedColormap.from_list() do the rest.

from matplotlib.colors import LinearSegmentedColormap
custom_cmap = LinearSegmentedColormap.from_list("my_cmap", ["red", "black", "white"])
custom red-black-white colormap

This colormap transitions smoothly (linearly) from red to black to white at regular intervals along the scale. It's a colormap I find useful for visualizing arrays of values, but doesn't currently exist in the Matplotlib library.

Whatever you do, please colormap responsibly. If you do this the Internet will get angry:

a horrible colormap