How to add a colorbar in Matplotlib

Color-mapped Matplotlib plots need a visible scale when color carries numeric meaning. A colorbar shows how data values map to the colormap, so a heatmap, image, contour plot, or colored scatter plot can be read without guessing what each color means.

A colorbar is attached to the plotted object that owns the colormap and normalization. With the object-oriented interface, keep the return value from imshow(), scatter(), contourf(), or pcolormesh() and pass it to fig.colorbar() so the scale uses the same data range as the plot.

A saved heatmap-style PNG should show a vertical colorbar labeled with the plotted units. The same pattern works for other scalar mappables; attach the colorbar to the returned artist and label the scale in the units readers need.

Steps to add a Matplotlib colorbar:

  1. Save the colorbar script as colorbar-add.py.
    colorbar-add.py
    from pathlib import Path
     
    import matplotlib
    import matplotlib.pyplot as plt
    import numpy as np
     
     
    output = Path("colorbar-add.png")
     
    measurements = np.array(
        [
            [18, 20, 23, 26, 28],
            [17, 21, 24, 27, 30],
            [16, 19, 22, 25, 29],
            [15, 18, 21, 24, 27],
        ]
    )
     
    fig, ax = plt.subplots(figsize=(6, 3.8), layout="constrained")
    image = ax.imshow(measurements, cmap="viridis", vmin=15, vmax=30)
     
    ax.set_title("Sensor temperature by rack")
    ax.set_xlabel("Rack column")
    ax.set_ylabel("Rack row")
    ax.set_xticks(range(measurements.shape[1]))
    ax.set_yticks(range(measurements.shape[0]))
     
    colorbar = fig.colorbar(image, ax=ax, label="Temperature (deg C)")
     
    fig.savefig(output, dpi=160)
    plt.close(fig)
     
    print(f"matplotlib {matplotlib.__version__}")
    print(f"colorbar label: {colorbar.ax.get_ylabel()}")
    print(f"colorbar orientation: {colorbar.orientation}")
    print(f"saved: {output}")
    print(f"bytes: {output.stat().st_size}")

    image is the AxesImage returned by imshow(). Passing that object to fig.colorbar() keeps the colorbar tied to the same colormap and value range.

  2. Run the script from the Python environment that has Matplotlib installed.
    $ python colorbar-add.py
    matplotlib 3.11.0
    colorbar label: Temperature (deg C)
    colorbar orientation: vertical
    saved: colorbar-add.png
    bytes: 34561

    The byte count can change with Matplotlib, font, backend, or DPI differences. A nonzero byte count confirms that the PNG file was written.

  3. Open colorbar-add.png and confirm the vertical scale appears next to the heatmap.

    The label should read Temperature (deg C), and the tick values should span the same 15 to 30 range used by vmin and vmax.

  4. Reuse the returned mappable when adding a colorbar to scatter, contour, or mesh plots.
    points = ax.scatter(x, y, c=scores, cmap="viridis")
    fig.colorbar(points, ax=ax, label="Score")

    Use the artist returned by the plotting call, such as points from ax.scatter() or a ContourSet from ax.contourf(). Passing raw data to fig.colorbar() does not carry the plot's colormap and normalization.

  5. Remove the sample files when they were created only for testing.
    $ rm colorbar-add.py colorbar-add.png