Colormaps¶
A Colormap maps values between 0 and 1 to colors. Colormaps come in two flavors:
- ListedColormap - best for a discrete color mapping
- LinearSegmentedColormap - best for a continuous color mapping
ListedColormap¶
As an example, Dark2 is a ListedColormap with 8 distinct colors.
We can fetch the colormap using the matplotlib.colormaps
registry (
or pyplot.colormaps
). For example,
Deprecation of get_cmap()
function
Lots of old code use matplotlib.cm.get_cmap()
, but this technique will soon be deprecated.
We can inspect its colors via the .colors
attribute.
When we make a scatter plot, we can use cmap=plt.colormaps["Dark2"]
to apply the Dark2 Colormap.
How it works
- The
c
values are normalized to range [0, 1] using the default formula
- The normalized
c
values are then mapped to colors using the chosen color map.
In the example above, the c=[0,1,2,0,1]
is normalized into cnorm = [0., 0.5, 1., 0., 0.5]
. Those normalized values map to the following colors:
LinearSegmentedColormap¶
LinearSegmentedColormaps behave much like ListedColormaps, except they don't have a .colors
attribute. For example, consider the LinearSegmentedColormap rainbow.
We can use cmap=plt.colormaps["rainbow"]
to apply the rainbow Colormap to a scatter plot.
How it works
- The
c
values are normalized to range [0, 1] using the default formula c n o r m a l i z e d = c − c m i n c m a x − c m i n c_{normalized} = \frac{c - c_{min}}{c_{max} - c_{min}} cnormalized=cmax−cminc−cmin - The normalized
c
values are then mapped to colors using the chosen color map.
In the example above, the c=[0,1,2,0,1]
is normalized into cnorm = [0., 0.5, 1., 0., 0.5]
. Those normalized values map to the following colors: