Colormaps in Matplotlib
Learn how to use colormaps in Matplotlib to represent numerical values through different colours. Understand sequential, diverging and qualitative colormaps, custom colour ranges, reversed colormaps and colour mapping in plots.
1. Learning Objectives
After completing this lesson, you will be able to:
- Understand what colormaps are and why they are used.
- Identify different types of Matplotlib colormaps.
- Use built-in colormaps such as viridis, plasma and inferno.
- Apply colormaps to scatter plots and other visualisations.
- Understand how numerical values are mapped to colours.
- Control colour ranges using normalization.
- Use reversed and custom colormaps.
- Create discrete colormaps for categorical ranges.
2. Introduction to Colormaps
A colormap is a collection of colours used to represent numerical values in a visualisation. It converts numerical data into colours so that differences in values can be understood easily.
For example, in a temperature visualisation, lower temperatures may be represented using blue colours, while higher temperatures may be represented using red or yellow colours.
What is Colour Mapping?
Colour mapping is the process of converting numerical data into corresponding colours using a colormap and a normalization method.
Numerical Data
|
v
Normalization
|
v
Colormap
|
v
Colour Representation
Conceptual flow of numerical data through a colormap.
3. Why Do We Use Colormaps?
Colormaps help users identify patterns, differences and relationships in numerical data. They are especially useful when a plot contains many data points or represents a large range of values.
Common Applications
- Temperature and weather visualisations.
- Scientific and engineering data analysis.
- Heatmaps and image processing.
- Geographical and geographical elevation maps.
- Machine learning data visualisation.
- Statistical and financial analysis.
Example: Temperature Values
Suppose we have temperature values from 10 to 50 degrees. A colormap can represent these values using a colour gradient.
Temperature: 10 20 30 40 50
Colour: Blue Cyan Green Yellow Red
A conceptual example showing how values can be represented using different colours.
4. Types of Colormaps
Matplotlib provides different types of colormaps. Each type is designed for a particular kind of data.
4.1 Sequential Colormaps
Sequential colormaps are used when data values move from low to high. They generally use a continuous progression from light to dark or from one colour to another.
Common sequential colormaps include:
viridisplasmainfernomagmacividisBluesGreens
import matplotlib.pyplot as plt
import numpy as np
data = np.arange(100).reshape(10, 10)
plt.imshow(data, cmap='viridis')
plt.colorbar()
plt.title('Sequential Colormap')
plt.show()
Expected Output:
A 10 x 10 colour-mapped image is displayed.
Lower values appear in one part of the viridis colour range,
while higher values appear in another part.
A colourbar shows the relationship between values and colours.
4.2 Diverging Colormaps
Diverging colormaps are useful when data has a meaningful central value, such as zero, an average or a target value. They use two different colour directions around that centre.
Common diverging colormaps include:
coolwarmRdBuPiYGBrBGseismic
import matplotlib.pyplot as plt
import numpy as np
data = np.linspace(-5, 5, 100).reshape(10, 10)
plt.imshow(data, cmap='coolwarm')
plt.colorbar()
plt.title('Diverging Colormap')
plt.show()
Expected Output:
A colour-mapped image is displayed using the coolwarm colormap.
Negative and positive values use different colour directions.
The middle value is represented near the centre of the colour range.
4.3 Qualitative Colormaps
Qualitative colormaps are designed for categorical data. They use distinct colours to identify different groups rather than showing a continuous numerical progression.
Common qualitative colormaps include:
tab10tab20Set1Set2Accent
import matplotlib.pyplot as plt
categories = ['Java', 'Python', 'C#', 'JavaScript']
values = [80, 95, 70, 85]
plt.bar(
categories,
values,
color=plt.colormaps['tab10'].colors[:4]
)
plt.title('Programming Language Scores')
plt.xlabel('Languages')
plt.ylabel('Scores')
plt.show()
Expected Output:
A bar chart with four categories is displayed.
Each bar uses a different colour from the tab10 colormap.
The chart compares the scores of four programming languages.
Conceptual comparison of sequential, diverging and qualitative colormaps.
Comparison of Colormap Types
| Type | Purpose | Examples |
|---|---|---|
| Sequential | Represent values from low to high. | viridis, plasma, inferno |
| Diverging | Compare values around a central point. | coolwarm, RdBu, seismic |
| Qualitative | Represent separate categories. | tab10, tab20, Set1 |
5. Using Built-in Colormaps
Matplotlib includes many built-in colormaps. You can apply
them using the cmap parameter in plotting
functions such as imshow(), scatter()
and contourf().
Example: Display Different Colormaps
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(10, 10)
colormaps = ['viridis', 'plasma', 'inferno', 'magma']
fig, axes = plt.subplots(2, 2, figsize=(9, 7))
for ax, cmap_name in zip(axes.flat, colormaps):
image = ax.imshow(data, cmap=cmap_name)
ax.set_title(cmap_name)
plt.tight_layout()
plt.show()
Expected Output:
A figure containing four image panels is displayed.
Each panel uses a different colormap:
viridis, plasma, inferno and magma.
The same numerical data is represented using different colour schemes.
Accessing the Colormap Registry
Matplotlib provides the matplotlib.colormaps
registry for accessing available colormaps.
import matplotlib as mpl
cmap = mpl.colormaps['viridis']
print(cmap.name)
print(cmap.N)
Expected Output:
viridis
256
The name property gives the colormap name.
The N property gives the number of colour
entries in the colormap.
Listing Available Colormaps
import matplotlib as mpl
for cmap_name in mpl.colormaps:
print(cmap_name)
Expected Output:
The available Matplotlib colormap names are printed.
The list includes names such as:
viridis
plasma
inferno
magma
cividis
coolwarm
tab10
tab20
The complete list depends on the installed Matplotlib version.
matplotlib.colormaps['viridis']
to access a colormap from the registry. This is the
recommended registry interface in modern Matplotlib.
6. Applying Colormaps to Scatter Plots
The scatter() function can use a colormap to
assign colours according to numerical values. The
c parameter provides the numerical values,
while cmap specifies the colormap.
Example: Scatter Plot with Colormap
import matplotlib.pyplot as plt
import numpy as np
x = np.random.rand(50)
y = np.random.rand(50)
values = np.random.rand(50)
plt.scatter(
x,
y,
c=values,
cmap='viridis',
s=80
)
plt.colorbar(label='Value')
plt.title('Scatter Plot with Colormap')
plt.xlabel('X Values')
plt.ylabel('Y Values')
plt.show()
Expected Output:
A scatter plot containing 50 points is displayed.
Each point receives a colour based on its numerical value.
A colourbar displays the relationship between values and colours.
Important Parameters
| Parameter | Description |
|---|---|
c |
Numerical values used to determine point colours. |
cmap |
Selects the colormap. |
s |
Controls marker size. |
vmin |
Defines the lower limit of the colour scale. |
vmax |
Defines the upper limit of the colour scale. |
norm |
Controls how values are normalized before colour mapping. |
7. Colormap Normalization
Normalization converts data values into a standard range before they are passed to a colormap. Matplotlib commonly uses values between 0 and 1 for this mapping process.
For example, if the data range is from 10 to 100, normalization maps 10 to 0 and 100 to 1. Intermediate values are mapped proportionally.
7.1 Using Normalize
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np
data = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
norm = colors.Normalize(
vmin=10,
vmax=100
)
normalized_data = norm(data)
print(normalized_data)
Expected Output:
[0. 0.11111111 0.22222222 0.33333333
0.44444444 0.55555556 0.66666667 0.77777778
0.88888889 1. ]
The Normalize() class maps values between
the specified minimum and maximum limits into the
normalized range.
7.2 Using vmin and vmax
You can directly control the colour range in plotting
functions by using vmin and vmax.
import matplotlib.pyplot as plt
import numpy as np
data = np.random.randint(0, 100, (10, 10))
plt.imshow(
data,
cmap='plasma',
vmin=0,
vmax=100
)
plt.colorbar()
plt.title('Colormap with Fixed Range')
plt.show()
Expected Output:
A 10 x 10 colour-mapped image is displayed.
The colour scale is fixed between 0 and 100.
The colourbar represents the selected numerical range.
vmin and vmax
values when you want to compare multiple plots using
the same colour scale.
8. Reversed Colormaps
Matplotlib allows you to reverse an existing colormap.
To reverse a colormap, add _r to its name.
For example, viridis_r is the reversed
version of viridis.
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(10, 10)
fig, axes = plt.subplots(1, 2, figsize=(9, 4))
axes[0].imshow(data, cmap='viridis')
axes[0].set_title('Viridis')
axes[1].imshow(data, cmap='viridis_r')
axes[1].set_title('Viridis Reversed')
plt.tight_layout()
plt.show()
Expected Output:
Two image panels are displayed.
The first panel uses the normal viridis colormap.
The second panel uses the reversed viridis_r colormap.
The colour progression runs in the opposite direction.
Conceptual comparison of a colormap and its reversed version.
9. Discrete Colormaps
A discrete colormap contains a fixed number of separate colours. It is useful when numerical values need to be grouped into specific ranges or categories.
9.1 Using ListedColormap
Matplotlib provides ListedColormap to create
a colormap from a list of specified colours.
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np
my_colors = ['blue', 'green', 'yellow', 'red']
my_cmap = colors.ListedColormap(my_colors)
data = np.random.randint(0, 4, (10, 10))
plt.imshow(data, cmap=my_cmap)
plt.colorbar()
plt.title('Custom Discrete Colormap')
plt.show()
Expected Output:
A 10 x 10 image is displayed using four distinct colours.
The colours are blue, green, yellow and red.
Each integer category is represented by a separate colour.
9.2 Using BoundaryNorm
The BoundaryNorm class maps values into
discrete intervals. Each interval can be assigned
a specific colour.
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np
data = np.random.randint(0, 100, (10, 10))
bounds = [0, 25, 50, 75, 100]
cmap = colors.ListedColormap([
'blue',
'green',
'yellow',
'red'
])
norm = colors.BoundaryNorm(
bounds,
cmap.N
)
plt.imshow(data, cmap=cmap, norm=norm)
plt.colorbar(
ticks=bounds,
label='Value Range'
)
plt.title('Discrete Colour Ranges')
plt.show()
Expected Output:
A colour-mapped image is displayed using four colour intervals.
Values from 0 to 25 use blue.
Values from 25 to 50 use green.
Values from 50 to 75 use yellow.
Values from 75 to 100 use red.
ListedColormap defines the available colours,
while BoundaryNorm determines how numerical
values are assigned to those colours.
10. Creating Custom Colormaps
Matplotlib allows you to create your own colormaps.
The LinearSegmentedColormap.from_list()
method creates a continuous colormap using a list of colours.
Example: Custom Colormap
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np
custom_colors = [
'navy',
'cyan',
'yellow',
'red'
]
custom_cmap = colors.LinearSegmentedColormap.from_list(
'my_custom_map',
custom_colors
)
data = np.random.rand(10, 10)
plt.imshow(data, cmap=custom_cmap)
plt.colorbar()
plt.title('Custom Colormap')
plt.show()
Expected Output:
A 10 x 10 image is displayed using a custom colour gradient.
The gradient transitions through navy, cyan, yellow and red.
A colourbar represents the numerical values.
Important Custom Colormap Methods
| Method / Class | Purpose |
|---|---|
ListedColormap() |
Creates a colormap from a fixed list of colours. |
LinearSegmentedColormap.from_list() |
Creates a continuous colour gradient from a list. |
Normalize() |
Maps numerical values into a normalized range. |
BoundaryNorm() |
Maps numerical values into discrete intervals. |
11. Choosing the Right Colormap
Choosing an appropriate colormap is important because colours affect how users understand the data. The colormap should match the type of information being displayed.
| Data Requirement | Recommended Type | Example |
|---|---|---|
| Low to high numerical values | Sequential | viridis |
| Positive and negative differences | Diverging | coolwarm |
| Different categories | Qualitative | tab10 |
| Scientific data comparison | Sequential or Diverging | cividis, RdBu |
| Fixed value groups | Discrete | ListedColormap |
viridis and cividis for
many continuous numerical visualisations. Select a
colormap that makes the important data differences clear.
12. Complete Practical Example
In this example, we create a scatter plot where each point receives a colour based on its value. We also add a colourbar to explain the colour scale.
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(42)
x = np.random.rand(100)
y = np.random.rand(100)
values = np.random.randint(10, 100, 100)
scatter = plt.scatter(
x,
y,
c=values,
cmap='plasma',
s=90,
alpha=0.8
)
plt.colorbar(
scatter,
label='Data Values'
)
plt.title('Student Performance Visualisation')
plt.xlabel('Study Hours')
plt.ylabel('Practice Hours')
plt.grid(True)
plt.show()
Expected Output:
A scatter plot with 100 points is displayed.
Each point uses a colour from the plasma colormap.
The colour represents the corresponding numerical data value.
A colourbar appears beside the plot with the label Data Values.
What We Learned from This Example
The c parameter assigns numerical values
to the scatter points. The cmap parameter
selects the plasma colormap. The colorbar()
function explains how colours correspond to values.
The alpha parameter controls transparency.
13. Common Mistakes and Solutions
| Common Mistake | Solution |
|---|---|
| Using an invalid colormap name. | Use an available name from matplotlib.colormaps. |
| Using qualitative colours for continuous data. | Choose a sequential or diverging colormap. |
| Comparing plots with different colour ranges. | Use consistent vmin and vmax values. |
| Not displaying a colourbar. | Use plt.colorbar() when the colour scale needs explanation. |
| Confusing colours with numerical values. | Use normalization to understand the mapping. |
| Using too many similar colours for categories. | Choose a qualitative colormap with clearly distinct colours. |
14. Practical Activity
Activity 1: Compare Built-in Colormaps
Create a 10 x 10 NumPy array and display it using viridis, plasma, inferno and magma colormaps. Compare the colour differences.
Activity 2: Reverse a Colormap
Create two image plots using coolwarm
and coolwarm_r. Observe the difference
in their colour progression.
Activity 3: Create a Custom Colormap
Use LinearSegmentedColormap.from_list()
to create a custom colormap with blue, green,
yellow and red colours.
Activity 4: Create a Discrete Colormap
Use ListedColormap and
BoundaryNorm to represent numerical
values using four separate colour ranges.
15. Practice Questions
- What is a colormap in Matplotlib?
- Why are colormaps used in data visualisation?
- What is the difference between sequential and diverging colormaps?
- What is a qualitative colormap?
- How can you access a built-in colormap?
- What is the purpose of the
cmapparameter? - What is normalization in colour mapping?
- How can you reverse a colormap?
- What is the difference between ListedColormap and BoundaryNorm?
- How can you create a custom colormap?
Summary
A colormap is a collection of colours used to represent numerical values in Matplotlib visualisations. It helps users understand patterns, differences and relationships in data through colour.
Matplotlib provides three major categories of colormaps: sequential, diverging and qualitative. Sequential colormaps represent continuous values, diverging colormaps compare values around a central point, and qualitative colormaps represent separate categories.
Built-in colormaps such as viridis, plasma, inferno, magma,
cividis and coolwarm can be accessed through the
Matplotlib colormap registry. The cmap
parameter applies colormaps to different plotting functions.
Normalization converts numerical values into a standard range before colour mapping. The Normalize class, vmin and vmax parameters help control the colour range.
Matplotlib also supports reversed colormaps, discrete colormaps and custom colormaps. ListedColormap, BoundaryNorm and LinearSegmentedColormap provide additional control over colour representation.
Selecting the correct colormap improves the readability and interpretation of data visualisations. Always choose a colormap according to the type and purpose of your data.