Colorbars in Matplotlib
Learn how to add and customise colorbars in Matplotlib. Understand colorbar labels, orientation, ticks, formatting, position, size and spacing. Explore how colorbars explain the relationship between numerical values and colours.
1. Learning Objectives
After completing this lesson, you will be able to:
- Understand what a colorbar is.
- Add colorbars to heatmaps and scatter plots.
- Use the plt.colorbar() function.
- Set colorbar labels and titles.
- Change colorbar orientation.
- Customise colorbar ticks and tick labels.
- Format colorbar numerical values.
- Control colorbar size and position.
- Create shared colorbars for multiple plots.
- Use colorbar extensions and boundaries.
2. Introduction to Colorbars
A colorbar is a visual guide that explains how numerical values are represented by colours in a plot. It helps users understand the meaning of different colours used in heatmaps, scatter plots and image visualisations.
For example, a temperature heatmap may use blue for lower temperatures and red for higher temperatures. The colorbar displays the corresponding numerical temperature range.
Why Do We Use Colorbars?
A colorbar makes a visualisation easier to understand because it connects the colours in the plot with their actual numerical values.
Numerical Data
|
v
Colormap
|
v
Colour Representation
|
v
Colorbar
|
v
Understand Numerical Values
Conceptual heatmap and its corresponding colorbar.
3. Creating a Basic Colorbar
Matplotlib provides the plt.colorbar()
function to add a colorbar to a plot. It is commonly
used with image plots, heatmaps and scatter plots.
Basic Syntax
plt.colorbar(mappable=None, **kwargs)
Example: Basic Heatmap with Colorbar
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(10, 10)
plt.imshow(data, cmap='viridis')
plt.colorbar()
plt.title('Heatmap with Colorbar')
plt.show()
Expected Output:
A 10 x 10 heatmap is displayed.
The viridis colormap represents numerical values using colours.
A vertical colorbar appears beside the heatmap.
The plt.colorbar() function automatically
uses the current image or mappable object when one
is available.
4. Adding a Colorbar Label
A colorbar label describes the numerical information
represented by the colour scale. You can add a label
using the label parameter.
Example: Colorbar with Label
import matplotlib.pyplot as plt
import numpy as np
data = np.random.randint(0, 100, (10, 10))
plt.imshow(data, cmap='plasma')
plt.colorbar(label='Temperature (°C)')
plt.title('Temperature Heatmap')
plt.show()
Expected Output:
A temperature heatmap is displayed.
A vertical colorbar appears beside the heatmap.
The colorbar label is Temperature (°C).
Customising the Colorbar Label
You can use the colorbar object to customise the label font size, colour and rotation.
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(10, 10)
image = plt.imshow(data, cmap='viridis')
cbar = plt.colorbar(image)
cbar.set_label(
'Data Values',
fontsize=12,
color='darkblue'
)
plt.title('Custom Colorbar Label')
plt.show()
Expected Output:
A heatmap is displayed with a colorbar.
The colorbar label is Data Values.
The label uses a customised font size and colour.
5. Changing Colorbar Orientation
By default, Matplotlib displays a colorbar vertically.
You can change its orientation to horizontal by using
the orientation parameter.
5.1 Vertical Colorbar
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(10, 10)
image = plt.imshow(data, cmap='viridis')
plt.colorbar(
image,
orientation='vertical'
)
plt.title('Vertical Colorbar')
plt.show()
Expected Output:
A heatmap is displayed with a vertical colorbar
on the right side of the plot.
5.2 Horizontal Colorbar
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(10, 10)
image = plt.imshow(data, cmap='plasma')
plt.colorbar(
image,
orientation='horizontal'
)
plt.title('Horizontal Colorbar')
plt.show()
Expected Output:
A heatmap is displayed with a horizontal colorbar
below the plot.
Conceptual comparison of vertical and horizontal colorbars.
| Orientation | Position | Common Usage |
|---|---|---|
| vertical | Beside the plot | Heatmaps and image visualisations. |
| horizontal | Below or above the plot | Dashboards and wide visualisations. |
6. Customising Colorbar Ticks
Colorbar ticks indicate important numerical positions
along the colour scale. You can customise tick positions
using the set_ticks() method.
Example: Custom Colorbar Ticks
import matplotlib.pyplot as plt
import numpy as np
data = np.random.randint(0, 100, (10, 10))
image = plt.imshow(
data,
cmap='viridis',
vmin=0,
vmax=100
)
cbar = plt.colorbar(image)
cbar.set_ticks([0, 25, 50, 75, 100])
plt.title('Colorbar with Custom Ticks')
plt.show()
Expected Output:
A heatmap is displayed with a colorbar.
The colorbar displays ticks at:
0, 25, 50, 75 and 100.
Customising Tick Labels
You can also change the text displayed at each tick
using set_ticklabels(). The number of
labels should match the number of tick positions.
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(10, 10)
image = plt.imshow(data, cmap='plasma')
cbar = plt.colorbar(image)
cbar.set_ticks([0, 0.25, 0.50, 0.75, 1.0])
cbar.set_ticklabels([
'Low',
'Medium Low',
'Medium',
'Medium High',
'High'
])
plt.title('Custom Colorbar Tick Labels')
plt.show()
Expected Output:
A heatmap is displayed with a colorbar.
The numerical tick positions are labelled as:
Low, Medium Low, Medium, Medium High and High.
7. Formatting Colorbar Values
Colorbar values can be formatted to display decimals, percentages, currency or scientific notation. Matplotlib provides ticker formatters for this purpose.
7.1 Using FormatStrFormatter
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
data = np.random.rand(10, 10)
image = plt.imshow(data, cmap='viridis')
cbar = plt.colorbar(image)
cbar.ax.yaxis.set_major_formatter(
ticker.FormatStrFormatter('%.2f')
)
plt.title('Colorbar with Decimal Formatting')
plt.show()
Expected Output:
A heatmap is displayed with a colorbar.
Colorbar tick labels are formatted to two decimal places.
Example labels include 0.00, 0.25, 0.50 and 0.75.
7.2 Using Percent Formatting
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
data = np.random.rand(10, 10)
image = plt.imshow(
data,
cmap='plasma',
vmin=0,
vmax=1
)
cbar = plt.colorbar(image)
cbar.ax.yaxis.set_major_formatter(
ticker.PercentFormatter(xmax=1)
)
plt.title('Percentage Colorbar')
plt.show()
Expected Output:
A heatmap is displayed with a colorbar.
The colorbar values are displayed as percentages.
Example labels include 0%, 25%, 50%, 75% and 100%.
Common Formatters
| Formatter | Purpose |
|---|---|
FormatStrFormatter |
Formats values using a format string. |
PercentFormatter |
Displays values as percentages. |
ScalarFormatter |
Formats scalar numerical values. |
StrMethodFormatter |
Formats tick labels using Python format strings. |
8. Controlling Colorbar Size and Spacing
Matplotlib provides parameters such as
shrink, aspect,
fraction and pad
to control colorbar appearance and spacing.
Important Parameters
| Parameter | Description |
|---|---|
shrink |
Scales the colorbar length. |
aspect |
Controls the ratio of the colorbar's long dimension to its short dimension. |
fraction |
Controls the fraction of the parent axes allocated to the colorbar. |
pad |
Controls the space between the plot and colorbar. |
location |
Specifies the side where the colorbar is placed in supported Matplotlib versions. |
Example: Custom Colorbar Size
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(10, 10)
image = plt.imshow(data, cmap='viridis')
plt.colorbar(
image,
shrink=0.7,
aspect=20,
pad=0.05
)
plt.title('Custom Colorbar Size')
plt.show()
Expected Output:
A heatmap is displayed with a shorter vertical colorbar.
The colorbar has a customised aspect ratio.
The gap between the heatmap and colorbar is controlled by pad.
Example: Horizontal Colorbar Size
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(10, 10)
image = plt.imshow(data, cmap='plasma')
plt.colorbar(
image,
orientation='horizontal',
shrink=0.8,
pad=0.15
)
plt.title('Horizontal Colorbar')
plt.show()
Expected Output:
A heatmap is displayed with a horizontal colorbar.
The colorbar length is reduced using shrink.
The vertical gap is controlled by pad.
9. Controlling Colorbar Position
You can control the position of a colorbar using
the location parameter in supported
Matplotlib versions. Common positions include
right, left, top and bottom.
Example: Colorbar on the Left
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(10, 10)
image = plt.imshow(data, cmap='viridis')
plt.colorbar(
image,
location='left'
)
plt.title('Colorbar on Left')
plt.show()
Expected Output:
A heatmap is displayed.
The vertical colorbar appears on the left side of the plot.
Example: Colorbar at the Top
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(10, 10)
image = plt.imshow(data, cmap='plasma')
plt.colorbar(
image,
location='top',
orientation='horizontal'
)
plt.title('Colorbar at Top')
plt.show()
Expected Output:
A heatmap is displayed.
A horizontal colorbar appears above the plot.
location parameter is available in
modern Matplotlib versions. When working with an older
version, use the appropriate axes placement methods.
10. Colorbar with Scatter Plots
Colorbars are not limited to heatmaps. They can also explain the colours used in scatter plots. Each point can receive a colour according to a numerical value.
Example: Scatter Plot with Colorbar
import matplotlib.pyplot as plt
import numpy as np
x = np.random.rand(50)
y = np.random.rand(50)
values = np.random.randint(0, 100, 50)
scatter = plt.scatter(
x,
y,
c=values,
cmap='viridis',
s=80
)
plt.colorbar(
scatter,
label='Data Values'
)
plt.title('Scatter Plot with Colorbar')
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 according to its numerical value.
A colorbar explains the relationship between colours and values.
plt.scatter() to plt.colorbar().
This ensures the colorbar uses the same colour mapping
as the scatter points.
11. Creating a Shared Colorbar
When multiple plots use the same numerical colour scale, a single shared colorbar can be used to explain all the plots. This helps keep the figure clean and organised.
Example: Shared Colorbar for Multiple Heatmaps
import matplotlib.pyplot as plt
import numpy as np
data1 = np.random.rand(10, 10)
data2 = np.random.rand(10, 10)
fig, axes = plt.subplots(1, 2, figsize=(9, 4))
image1 = axes[0].imshow(
data1,
cmap='viridis',
vmin=0,
vmax=1
)
image2 = axes[1].imshow(
data2,
cmap='viridis',
vmin=0,
vmax=1
)
axes[0].set_title('Dataset 1')
axes[1].set_title('Dataset 2')
fig.colorbar(
image1,
ax=axes,
label='Values'
)
plt.tight_layout()
plt.show()
Expected Output:
Two heatmaps are displayed side by side.
Both heatmaps use the viridis colormap.
A shared colorbar explains their common numerical range.
12. Colorbar Extensions
Colorbar extensions indicate that values exist beyond
the displayed colour range. Matplotlib provides the
extend parameter for this purpose.
Common values include:
neither- No extensions are displayed.min- An extension is displayed at the minimum end.max- An extension is displayed at the maximum end.both- Extensions are displayed at both ends.
Example: Colorbar with Extensions
import matplotlib.pyplot as plt
import numpy as np
data = np.random.randint(-20, 120, (10, 10))
image = plt.imshow(
data,
cmap='coolwarm',
vmin=0,
vmax=100
)
plt.colorbar(
image,
extend='both',
label='Measurement'
)
plt.title('Colorbar with Extensions')
plt.show()
Expected Output:
A heatmap is displayed using the coolwarm colormap.
The colour range is limited from 0 to 100.
The colorbar displays extension indicators at both ends
to represent values outside the selected range.
Conceptual illustration of colorbar extensions.
13. Complete Practical Example
In this example, we create a temperature heatmap with a customised colorbar. The colorbar displays temperature values in degrees Celsius with custom ticks and labels.
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
temperature = np.array([
[15, 20, 25, 30, 35],
[18, 22, 28, 32, 38],
[12, 19, 24, 29, 34],
[16, 21, 27, 33, 40],
[10, 17, 23, 31, 36]
])
fig, ax = plt.subplots(figsize=(8, 5))
image = ax.imshow(
temperature,
cmap='coolwarm',
vmin=0,
vmax=50
)
cbar = fig.colorbar(
image,
ax=ax,
orientation='vertical',
shrink=0.85,
pad=0.04
)
cbar.set_label(
'Temperature (°C)',
fontsize=12
)
cbar.set_ticks([0, 10, 20, 30, 40, 50])
cbar.ax.yaxis.set_major_formatter(
ticker.FormatStrFormatter('%d°C')
)
ax.set_title('Temperature Distribution')
ax.set_xlabel('Location X')
ax.set_ylabel('Location Y')
plt.tight_layout()
plt.show()
Expected Output:
A 5 x 5 temperature heatmap is displayed.
The coolwarm colormap represents temperature values.
A vertical colorbar appears beside the heatmap.
The colorbar label is Temperature (°C).
The colorbar displays ticks from 0°C to 50°C.
What We Learned
We created a temperature array using NumPy and displayed it with imshow(). The fig.colorbar() method added a colorbar to the selected axes. We customised its label, tick positions, numerical formatting, size and spacing.
14. Common Mistakes and Solutions
| Common Mistake | Solution |
|---|---|
| Colorbar is not displayed. | Pass a valid mappable object to colorbar(). |
| Colorbar represents the wrong plot. | Pass the correct image or scatter object. |
| Tick labels do not match tick positions. | Use the same number of positions and labels. |
| Colorbar is too long or too short. | Adjust the shrink parameter. |
| Colorbar is too far from the plot. | Adjust the pad parameter. |
| Values are difficult to understand. | Add a meaningful colorbar label. |
| Multiple plots use different colour ranges. | Use consistent normalization limits. |
| Colorbar labels are difficult to read. | Customise font size and tick formatting. |
15. Practical Activity
Activity 1: Create a Basic Colorbar
Create a heatmap using a NumPy array and add a
colorbar using plt.colorbar().
Activity 2: Customise Colorbar Labels
Add a label named Temperature (°C) and customise its font size.
Activity 3: Change Colorbar Orientation
Create vertical and horizontal colorbars and compare their positions.
Activity 4: Customise Ticks
Display colorbar ticks at 0, 20, 40, 60, 80 and 100.
Activity 5: Create a Shared Colorbar
Create two heatmaps using the same colormap and numerical range. Add one shared colorbar.
Activity 6: Format Colorbar Values
Use PercentFormatter to display colorbar values as percentages.
16. Practice Questions
- What is a colorbar in Matplotlib?
- Why do we use plt.colorbar()?
- How can you add a label to a colorbar?
- What is the default colorbar orientation?
- How can you create a horizontal colorbar?
- How can you customise colorbar tick positions?
- What is the purpose of FormatStrFormatter?
- How can you change the size of a colorbar?
- What is the purpose of the pad parameter?
- How can you create a shared colorbar?
- What is the purpose of the extend parameter?
- How can you add a colorbar to a scatter plot?
Summary
A colorbar is a visual guide that explains the relationship between numerical values and colours in a Matplotlib plot. It is commonly used with heatmaps, image visualisations and scatter plots.
The plt.colorbar() function adds a colorbar to a plot. The label parameter and set_label() method can be used to describe the numerical information represented by the colour scale.
Colorbar orientation can be changed between vertical and horizontal. The set_ticks() and set_ticklabels() methods help customise tick positions and labels.
Matplotlib provides ticker formatters such as FormatStrFormatter and PercentFormatter to control the display of numerical values on a colorbar.
Parameters such as shrink, aspect, fraction and pad help control colorbar size and spacing. The location parameter can be used to select its position in supported Matplotlib versions.
Colorbars can also be used with scatter plots and shared across multiple axes. The extend parameter indicates values outside the selected colour range.
Properly customised colorbars make data visualisations easier to understand and improve the presentation of numerical information.