Matplotlib colorbar() Function
Matplotlib Reference Documentation
colorbar()Used to add a colorbar (color scale) to a chart, mapping colors to a range of values.
The colorbar is an essential element used together with the colormap, allowing readers to map colors back to the original data values.
Function Definition
matplotlib.pyplot.colorbar(mappable=None, cax=None, ax=None, **kwargs)
Figure.colorbar(mappable=None, cax=None, ax=None, use_gridspec=True,
**kwargs)
Parameter Description
| Parameter | Description |
|---|---|
| mappable | A mappable color object, such as the return value of imshow(), scatter(), contourf() (required) |
| ax | The Axes to which the colorbar is attached (recommended, automatically adjusts the layout) |
| cax | A dedicated colorbar Axes (used for fine control) |
| shrink | The scaling ratio of the colorbar relative to the Axes, default 1.0, commonly 0.8 |
| aspect | The aspect ratio of the colorbar, default 20 |
| label | Label text for the colorbar |
| orientation | 'vertical' (default) or 'horizontal' |
| ticks | Custom tick positions |
| extend | 'neither'/'both'/'min'/'max', color indication for out-of-range values |
| pad | Spacing between the colorbar and the Axes |
Usage
fig.colorbar(im, ax=ax)Is the recommended approach, as it automatically adjusts the subplot layout to make room for the colorbar.
Usage Examples
Example 1: imshow + Vertical Colorbar
Example
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(10, 10)
fig, ax = plt.subplots(figsize=(6, 5), layout='constrained')
im = ax.imshow(data, cmap='viridis', aspect='auto')
# Add a vertical colorbar
cbar = fig.colorbar(im, ax=ax, label='Value', shrink=0.8)
ax.set_title('imshow with Colorbar')
ax.set_xlabel('Column')
ax.set_ylabel('Row')
plt.show()
import numpy as np
data = np.random.rand(10, 10)
fig, ax = plt.subplots(figsize=(6, 5), layout='constrained')
im = ax.imshow(data, cmap='viridis', aspect='auto')
# Add a vertical colorbar
cbar = fig.colorbar(im, ax=ax, label='Value', shrink=0.8)
ax.set_title('imshow with Colorbar')
ax.set_xlabel('Column')
ax.set_ylabel('Row')
plt.show()
Example 2: Horizontal Colorbar + Custom Ticks
Example
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) * np.cos(Y)
fig, ax = plt.subplots(figsize=(7, 5), layout='constrained')
im = ax.contourf(X, Y, Z, levels=15, cmap='coolwarm')
# Horizontal colorbar (below the Axes)
cbar = fig.colorbar(im, ax=ax,
orientation='horizontal',
label='Amplitude',
shrink=0.8,
pad=0.08,
ticks=[-0.8, -0.4, 0, 0.4, 0.8])
ax.set_title('Horizontal Colorbar')
ax.set_xlabel('X')
ax.set_ylabel('Y')
plt.show()
import numpy as np
x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) * np.cos(Y)
fig, ax = plt.subplots(figsize=(7, 5), layout='constrained')
im = ax.contourf(X, Y, Z, levels=15, cmap='coolwarm')
# Horizontal colorbar (below the Axes)
cbar = fig.colorbar(im, ax=ax,
orientation='horizontal',
label='Amplitude',
shrink=0.8,
pad=0.08,
ticks=[-0.8, -0.4, 0, 0.4, 0.8])
ax.set_title('Horizontal Colorbar')
ax.set_xlabel('X')
ax.set_ylabel('Y')
plt.show()
Example 3: scatter + Colorbar
Example
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(42)
n = 100
x = np.random.rand(n) * 10
y = np.random.rand(n) * 10
values = np.random.rand(n) * 100 # Data for color mapping
fig, ax = plt.subplots(figsize=(7, 5), layout='constrained')
sc = ax.scatter(x, y, c=values, cmap='YlOrRd',
s=100, edgecolors='white', linewidth=0.5)
# The PathCollection returned by scatter can also be passed to colorbar
cbar = fig.colorbar(sc, ax=ax, label='Score', shrink=0.8)
ax.set_title('Scatter with Colorbar')
ax.set_xlabel('X')
ax.set_ylabel('Y')
plt.show()
import numpy as np
np.random.seed(42)
n = 100
x = np.random.rand(n) * 10
y = np.random.rand(n) * 10
values = np.random.rand(n) * 100 # Data for color mapping
fig, ax = plt.subplots(figsize=(7, 5), layout='constrained')
sc = ax.scatter(x, y, c=values, cmap='YlOrRd',
s=100, edgecolors='white', linewidth=0.5)
# The PathCollection returned by scatter can also be passed to colorbar
cbar = fig.colorbar(sc, ax=ax, label='Score', shrink=0.8)
ax.set_title('Scatter with Colorbar')
ax.set_xlabel('X')
ax.set_ylabel('Y')
plt.show()
FAQ
Colorbar causing inconsistent subplot sizes?
Use thelayout='constrained'parameter to handle it automatically.
Or call on the Figure,fig.colorbar(im, ax=axes)passing in a list of all affected Axes.
How to share one colorbar among multiple subplots?
When associating one colorbar with multiple subplots, pass inax=axes_list。
Other Extensions