Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 57 ยท Line Plots and Basic Styling

Colormaps and Color Normalization

Choose the right Matplotlib colormap, understand why viridis beats jet, and control the mapping with Normalize, LogNorm, TwoSlopeNorm and colorbars.

A colormap turns numbers into colors. Whenever a chart encodes a value by color (a heatmap, a scatter plot colored by a third variable, a filled contour), Matplotlib does two steps: a norm squeezes your data range into the interval from 0 to 1, and a colormap looks up the color at that position. Both steps are yours to control, and the choices change what viewers believe the data says.

This lesson explains the four families of colormaps, why some are misleading, and how to bend the mapping with normalizations. You will see the same ideas again in scatter plots and heatmaps. For single colors, see colors, line styles and markers.

Data to color in two steps

Norm Maps your data range to 0 to 1.
Colormap Maps 0 to 1 to a color.
Colorbar Shows the key to the reader.

Change the norm to change contrast, not the data.

1 / 2

Picking the right family

  • Sequential maps (viridis, plasma, Blues, magma) run from light to dark or dark to light. Use them for values that go from low to high, such as temperature or counts.
  • Diverging maps (coolwarm, RdBu, PiYG) have a neutral middle and two opposite hues. Use them when the data has a meaningful center, such as a change from zero, a correlation from -1 to 1, or deviation from an average.
  • Cyclic maps (twilight, hsv) end where they begin. Use them for angles, phases and times of day.
  • Qualitative maps (tab10, Set2, Pastel1) are a handful of unrelated colors. Use them for categories with no order, never for continuous values.

The mapping name goes into the cmap argument: ax.imshow(data, cmap="viridis"). The default for most image and scatter functions is viridis.

jet (the rainbow from blue to red) used to be the default and still appears in older code. It has two problems. Its brightness goes up and down along the scale, so a smooth gradient in your data appears to have bands and edges that are not there. It also depends heavily on distinguishing hues, which fails for many people with color-vision deficiency. viridis was designed to be perceptually uniform: equal steps in the data look like equal steps in color, its lightness increases steadily, and it stays readable in grayscale.

You can test any map by converting it to grayscale and checking that it still ranks values correctly.

Python viridis versus jet in grayscale

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at the right-hand column. viridis becomes a clean dark-to-light ramp, while jet shows a bright band in the middle and darker ends on both sides: in grayscale, very different values look alike.

Colormap objects and reversed maps

plt.get_cmap("viridis") returns a Colormap object. You can call it like a function with numbers between 0 and 1 (or an array of them) to get RGBA colors, which is useful for coloring lines by value. Append _r to a name to reverse the map: "viridis_r" runs from yellow to purple. Reverse a map when high values should be dark, for example on a light background where bright is "empty".

Python
cmap = plt.get_cmap("plasma")
cmap(0.0)                 # RGBA at the low end
cmap(np.linspace(0, 1, 5))  # five evenly spaced colors, shape (5, 4)

ax.set_prop_cycle or manual color lists can use these samples to give each of many lines a color from a sequential map, so their order is visible.

Building your own colormaps

The built-in colormaps cover most needs, but sometimes you want your brand colours, a colour scale that ends at a meaningful value or exactly five distinct colours for five categories. Matplotlib gives you two classes for this, both in matplotlib.colors:

  • ListedColormap(colors) is a discrete colormap: a plain list of colours, one per band. The first colour is used for the lowest values, the last for the highest, and nothing is blended in between. It fits categories and binned data.
  • LinearSegmentedColormap.from_list(name, colors) is a continuous colormap: it blends smoothly between the colours you list. Two colours give a simple ramp, three or more give a route through colour space. Add numbers to place the colours unevenly: from_list("name", [(0, "white"), (0.3, "gold"), (1, "darkred")]).

Colours may be names ("navy"), hex codes ("#2a9d8f") or RGB tuples. Remember what you learned about picking the right family: a two-colour ramp from light to dark is a good sequential map, while a map with a pale middle colour between two hues is diverging.

Python ListedColormap and LinearSegmentedColormap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A discrete colormap needs a way to decide which value gets which colour. BoundaryNorm(boundaries, ncolors) assigns the ranges between the boundaries to the colours in order (four colours need five boundaries). Without it, the values are spread evenly over the colour list from the data's minimum to its maximum, which also works but gives uneven, hard-to-explain band edges.

Colours sampled from an existing map

You can also build a list from a built-in colormap: calling a colormap with numbers between 0 and 1 returns RGBA colours, so plt.cm.viridis(np.linspace(0, 1, 5)) gives five evenly spaced colours. That is the easy way to colour five lines, five bars or five groups consistently, and to cut a piece out of a map (for example, only the darker half, with np.linspace(0.3, 1, 256), so that the palest colour does not disappear on a white background).

Python Colours from a list, and a trimmed colormap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

matplotlib.colormaps.register(cmap, name=...) makes your colormap available by name, so imshow(..., cmap="BluesDark") works everywhere in the same session, like the built-in ones. Two more tricks: cmap.with_extremes(under="navy", over="gold", bad="lightgray") sets the colours for values below, above and missing (NaN), and cmap.reversed() flips it. Always add a colorbar so readers can decode a custom palette, and test it in grayscale and for colour-blind viewers (see Choosing accessible colors).

Normalization: from data to 0-1

By default, a color-mapped plot stretches the colormap from the smallest to the largest value. A single outlier can then squash everything else into one color. A norm gives you control.

  • Normalize(vmin, vmax) is linear. Passing vmin and vmax directly to a plotting function does the same job, and it also fixes the range so several plots are comparable.
  • LogNorm(vmin, vmax) uses a logarithmic scale. Use it when values span several orders of magnitude. All values must be positive.
  • TwoSlopeNorm(vcenter=0, vmin, vmax) places the center of a diverging map at a chosen value, even when the data is lopsided, such as temperatures from -5 to 35 with a center at 0.
Python The same data under three norms

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In the first panel almost the whole picture is dark purple because the peak dominates. With LogNorm the gradual falloff becomes visible. In the third panel white sits exactly at zero, so blue means negative and red means positive, even though the negative range is much smaller than the positive range.

Colorbars

A color-coded chart is meaningless without a key. fig.colorbar(mappable, ax=ax) adds one, where mappable is the object returned by imshow, scatter, pcolormesh or contourf. Useful options are label= for the title, shrink= for height, orientation="horizontal" and pad= for spacing. To place a bar once for several panels that share a norm, pass the list of axes: fig.colorbar(im, ax=axes.ravel().tolist()).

Python Qualitative, sequential and diverging side by side

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The left panel uses vmin=0, vmax=9 so that group numbers map onto the first few of the ten tab10 colors regardless of which groups appear. A legend with labelled entries is usually clearer than a bar for categories; see legends and grids.

Choosing accessible colors

Around one in twelve men has some form of color-vision deficiency, so red-green contrasts are risky. Good defaults are the perceptually uniform sequential maps (viridis, cividis, plasma, magma), which stay readable for most color-vision types. cividis is optimized for it. For diverging data prefer blue-orange or purple-green over red-green. Whenever color carries essential information, add a second cue such as labels, markers or patterns.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which colormap family is best for a correlation matrix with values from -1 to 1?

    A correlation has a natural center at 0 and two directions, which is exactly what a diverging map expresses.
  2. 2. What is the main problem with the jet colormap?

    jet is not perceptually uniform: lightness rises and falls, so smooth data appears to contain structure that is not there.
  3. 3. Your data spans values from 1 to 1,000,000 and most of the picture is one flat color. Which norm helps?

    LogNorm spaces colors by orders of magnitude, so small and large values both stay visible.
  4. 4. How do you reverse a colormap by name?

    Every built-in colormap has a reversed twin with the _r suffix.
  5. 5. What does fig.colorbar need as its first argument?

    The colorbar reads the colormap and norm from the mappable object, so it always matches the plot.

Summary

  • Color mapping has two steps: a norm maps data to 0-1, a colormap maps 0-1 to color.
  • Use sequential maps for ordered values, diverging maps for data with a meaningful center, cyclic maps for angles and qualitative maps for unordered categories.
  • Prefer perceptually uniform maps such as viridis over jet; check a map by converting it to grayscale.
  • Normalize, LogNorm and TwoSlopeNorm (or plain vmin/vmax) control contrast and the center point.
  • fig.colorbar(mappable, ax=ax) adds the key; _r reverses a map.
  • Choose colorblind-safe maps and add a second visual cue when color carries meaning.
  • ListedColormap (with BoundaryNorm) makes discrete colour bands, LinearSegmentedColormap.from_list blends colours smoothly, and matplotlib.colormaps.register gives a custom map a name.

Next, put words on your charts in Titles, Labels, Text and Math.