How to Add and Customize a Colorbar in Matplotlib

Add a colorbar with fig.colorbar, move it, shrink it to match the plot, label it, format its ticks, share one across subplots, and make discrete or zero-centered scales.

To add a colorbar in Matplotlib, keep the object returned by scatter, imshow, pcolormesh, or contourf and pass it to fig.colorbar(mappable, ax=ax). Use label to title it, location to move it, and shrink to resize it.

Quick Example

import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(21)
sqft = rng.uniform(500, 3500, 220)
age = rng.uniform(0, 80, 220)
price = 90 + 0.21 * sqft - 1.4 * age + rng.normal(0, 40, 220)

fig, ax = plt.subplots(figsize=(8, 4.8), layout="constrained")
points = ax.scatter(sqft, price, c=age, cmap="viridis", s=36)
fig.colorbar(points, ax=ax, label="Home age (years)")
ax.set_title("Sale price vs floor area, colored by age")
ax.set_xlabel("Floor area (sq ft)")
ax.set_ylabel("Price ($k)")
plt.show()

Matplotlib scatter plot of home sale price against floor area with a viridis colorbar labeled home age; older homes sit lower at the same size

The colorbar maps each point's color back to an age. At any given floor area the yellow (older) homes sell for less than the dark purple (newer) ones. The code targets Matplotlib 3.10 and 3.11.

What fig.colorbar Needs: a Mappable

A colorbar describes a mapping from numbers to colors, so it needs an artist that has one. Matplotlib calls that a mappable:

Plotting call What to pass to fig.colorbar
ax.scatter(..., c=values) the returned PathCollection
ax.imshow(data) the returned AxesImage
ax.pcolormesh(x, y, data) the returned QuadMesh
ax.contourf(x, y, data) the returned QuadContourSet
ax.hist2d(x, y) the fourth return value, result[3]

plt.colorbar() with no arguments uses the current image. If there isn't one, it raises RuntimeError: No mappable was found to use for colorbar creation. A line from ax.plot has no colormap, so it can't have a colorbar.

The color range comes from vmin/vmax (or a norm) on the plotting call, and the palette from cmap. Set those there rather than on the colorbar. Custom Colormaps in Matplotlib shows how to build your own.

Move the Colorbar: Right, Left, Top, or Bottom

location places the bar on any side of the axes. "top" and "bottom" make it horizontal automatically, so you don't need orientation="horizontal" as well.

x = np.linspace(-3, 3, 240)
y = np.linspace(-2, 2, 160)
X, Y = np.meshgrid(x, y)
elevation = (900 * np.exp(-((X - 1) ** 2 + (Y - 0.4) ** 2))
             + 600 * np.exp(-((X + 1.4) ** 2 / 0.8 + (Y + 0.6) ** 2 / 0.5)) + 120)

fig, axes = plt.subplots(2, 2, figsize=(9, 6.4), layout="constrained")
for ax, location in zip(axes.flat, ["right", "left", "top", "bottom"]):
    im = ax.imshow(elevation, cmap="terrain", origin="lower")
    fig.colorbar(im, ax=ax, location=location, label=f'location="{location}"')
    ax.set_xticks([])
    ax.set_yticks([])
plt.show()

Four copies of an elevation image, each with the colorbar on a different side: right, left, top, and bottom

Use pad to change the gap between the plot and the bar, as a fraction of the axes size. For example, pad=0.02 pulls it closer.

Resize the Colorbar and Match the Plot Height

Three arguments control the size:

  • shrink scales the bar's length: shrink=0.7 makes it 70% as long.
  • aspect is the ratio of length to width (default 20). Raise it for a thinner bar.
  • fraction is how much of the axes space the bar takes (default 0.15).

Images have a fixed aspect ratio, so a wide imshow often ends up shorter than its colorbar. Instead of tuning shrink by trial and error, create the colorbar axes with ax.inset_axes. Its bounds [x0, y0, width, height] are relative to the plot, so a height of 1 always matches.

fig, axes = plt.subplots(1, 2, figsize=(10, 3.6), layout="constrained")
for ax in axes:
    im = ax.imshow(elevation, cmap="terrain", origin="lower")
    ax.set_xticks([])
    ax.set_yticks([])
    if ax is axes[0]:
        fig.colorbar(im, ax=ax)
        ax.set_title("Default: taller than the image")
    else:
        cax = ax.inset_axes([1.03, 0, 0.045, 1])
        fig.colorbar(im, cax=cax)
        ax.set_title("inset_axes: same height")
plt.show()

Two elevation images: the default colorbar on the left is taller than the image, while the inset_axes colorbar on the right matches its height exactly

When you pass cax, the shrink and aspect arguments are ignored because the axes you made defines the size.

Colorbar Label, Ticks, and Number Format

fig.colorbar returns a Colorbar object. Its set_ticks() and set_label() methods change the ticks and title, and cbar.ax is a normal axes for anything else, such as tick label size.

from matplotlib.colors import LogNorm
from matplotlib.ticker import FuncFormatter

population = rng.lognormal(6, 1.6, (12, 20))
fig, ax = plt.subplots(figsize=(8, 4.6), layout="constrained")
im = ax.imshow(population, cmap="magma", norm=LogNorm(vmin=10, vmax=30_000))
cbar = fig.colorbar(im, ax=ax, extend="max", shrink=0.9)
cbar.set_ticks([10, 100, 1_000, 10_000, 30_000])
cbar.ax.yaxis.set_major_formatter(FuncFormatter(lambda v, _: f"{v:,.0f}"))
cbar.ax.tick_params(labelsize=10)
cbar.set_label("People per km² (log scale)", fontsize=11)
ax.set_title("Population density by grid cell")
plt.show()

Grid heatmap on a log color scale with colorbar ticks at 10, 100, 1,000, 10,000, and 30,000 and a pointed end for values above the maximum

  • LogNorm spaces the colors logarithmically, which keeps a few dense cells from washing out everything else.
  • extend="max" adds the pointed tip, telling the reader that some values are above vmax. Here the densest cell is about 64,000. Use "min" or "both" for the other ends.
  • For a simple number format you can skip the formatter and pass a string: format="{x:.1f}".
  • For a horizontal colorbar, format cbar.ax.xaxis instead of cbar.ax.yaxis.

One Shared Colorbar for Multiple Subplots

Two things are required. Every plot has to use the same norm, and ax gets the whole array of axes. Without the shared norm, each image scales to its own data and the colorbar only describes the last one.

from matplotlib.colors import Normalize

months = ["January", "April", "July"]
temps = [elevation / 100 * f + o + rng.normal(0, 0.15, elevation.shape)
         for f, o in [(-0.4, 4), (-0.5, 13), (-0.6, 27)]]
norm = Normalize(vmin=min(t.min() for t in temps), vmax=max(t.max() for t in temps))

fig, axes = plt.subplots(1, 3, figsize=(10, 3), layout="constrained")
for ax, month, data in zip(axes, months, temps):
    im = ax.imshow(data, cmap="plasma", norm=norm, origin="lower")
    ax.set_title(month)
    ax.set_xticks([])
    ax.set_yticks([])
fig.colorbar(im, ax=axes, label="Temperature (°C)", shrink=0.85)
plt.show()

Three temperature maps for January, April, and July sharing a single colorbar, shifting from dark blue to magenta to yellow

layout="constrained" makes room for the shared bar. tight_layout() doesn't handle a colorbar that spans several axes well.

Discrete and Zero-Centered Colorbars

BoundaryNorm splits the scale into bins with one color each. TwoSlopeNorm pins the middle of a diverging colormap to a value, usually zero, even when the data isn't symmetric.

from matplotlib.colors import BoundaryNorm, TwoSlopeNorm

anomaly = 2.6 * np.sin(X * 1.3) * np.cos(Y * 1.1) + 1.0 * np.exp(-((X - 2) ** 2 + Y ** 2))

fig, axes = plt.subplots(1, 2, figsize=(10, 3.4), layout="constrained")
bounds = [-3, -2, -1, 0, 1, 2, 3, 4]
cmap = plt.get_cmap("RdYlBu_r")
im = axes[0].imshow(anomaly, cmap=cmap, norm=BoundaryNorm(bounds, cmap.N), origin="lower")
fig.colorbar(im, ax=axes[0], ticks=bounds, shrink=0.85)
axes[0].set_title("Discrete bins: BoundaryNorm")

im = axes[1].imshow(anomaly, cmap="RdBu_r", origin="lower",
                    norm=TwoSlopeNorm(vcenter=0, vmin=anomaly.min(), vmax=anomaly.max()))
fig.colorbar(im, ax=axes[1], shrink=0.85, format="{x:+.0f}")
axes[1].set_title("Centered on zero: TwoSlopeNorm")
for ax in axes:
    ax.set_xticks([])
    ax.set_yticks([])
plt.show()

Temperature anomaly shown two ways: with seven discrete color bins on the left and a continuous red-blue scale centered on zero on the right

TwoSlopeNorm stretches each side independently, so one color step can mean a different amount above and below zero. If equal distances should look equally strong, use CenteredNorm(vcenter=0), which makes the range symmetric.

Practical Tips

  • Pass ax= every time. It tells Matplotlib which axes to take space from.
  • Use cbar.remove() to delete a colorbar, for example when redrawing in a loop or widget.
  • Prefer perceptually uniform maps (viridis, magma, plasma) for ordered data, and diverging maps only when the data has a meaningful center.
  • For heatmaps with Seaborn, pass cbar_kws={"label": "...", "shrink": 0.8} to sns.heatmap, as covered in styling Seaborn heatmaps.

Similar Topics