Matplotlib
colorbar
graph customization
data visualization
Python

Set Matplotlib colorbar size to match graph

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

Matplotlib colorbars often look slightly too tall, too short, or disconnected from the main axes when you rely on defaults. The fix depends on the plot layout and the API you use to create the colorbar. In practice, the most reliable solutions are attaching the colorbar to the correct axes and, for tighter control, using axes_grid1 or a dedicated gridspec layout.

Basic Attached Colorbar

For many cases, passing the plotted axes to fig.colorbar is enough.

python
1import numpy as np
2import matplotlib.pyplot as plt
3
4data = np.random.rand(20, 30)
5
6fig, ax = plt.subplots(figsize=(6, 4))
7im = ax.imshow(data, cmap="viridis")
8cbar = fig.colorbar(im, ax=ax)
9
10plt.show()

This tells Matplotlib which axes the colorbar belongs to, so sizing is tied to that plot instead of the whole figure.

Use fraction and pad for Small Adjustments

If the colorbar is close but not quite right, adjust its relative size and spacing.

python
1fig, ax = plt.subplots(figsize=(6, 4))
2im = ax.imshow(data, cmap="magma")
3cbar = fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04)
4
5plt.show()

These parameters are useful, but they are still relative heuristics. For precise matching, use an explicit colorbar axis.

Precise Control with make_axes_locatable

The axes_grid1 toolkit is often the cleanest way to make the colorbar height exactly track the plot axes.

python
1import numpy as np
2import matplotlib.pyplot as plt
3from mpl_toolkits.axes_grid1 import make_axes_locatable
4
5data = np.random.rand(20, 30)
6
7fig, ax = plt.subplots(figsize=(6, 4))
8im = ax.imshow(data, cmap="plasma")
9
10divider = make_axes_locatable(ax)
11cax = divider.append_axes("right", size="5%", pad=0.05)
12fig.colorbar(im, cax=cax)
13
14plt.show()

Because cax is created from the main axes divider, the colorbar tracks that axes height much more predictably.

Multi-Plot Layouts Need Explicit Axes Ownership

Colorbar sizing problems often appear in figures with several subplots. If you attach a colorbar to the wrong axes or to the whole figure without intention, it can span more than the graph you care about.

For one shared colorbar across several axes:

python
fig, axes = plt.subplots(1, 2, figsize=(8, 4))
ims = [ax.imshow(np.random.rand(10, 10), vmin=0, vmax=1) for ax in axes]
fig.colorbar(ims[0], ax=axes, shrink=0.9)

For one colorbar per axes, attach each colorbar separately.

Aspect Ratio Can Affect the Perceived Match

Even when the colorbar technically matches the axes, image aspect settings can make it look wrong.

python
ax.imshow(data, aspect="auto")

or

python
ax.imshow(data, aspect="equal")

The visual result changes because the plotting area itself changes. Always judge colorbar size after the final axes aspect is decided.

constrained_layout and tight_layout

Automatic layout systems help spacing, but they do not replace explicit colorbar ownership.

python
fig, ax = plt.subplots(constrained_layout=True)
im = ax.imshow(data)
fig.colorbar(im, ax=ax)

Use these tools to reduce clipping and overlap, then fix actual size alignment with proper axes setup.

Horizontal Colorbars Need the Same Discipline

The same rules apply when the colorbar is below the plot instead of to the right. Attach it to the correct axes and tune pad and fraction intentionally rather than relying on defaults.

python
cbar = fig.colorbar(im, ax=ax, orientation="horizontal", pad=0.12)

This is especially useful for wide heatmaps where a vertical colorbar wastes horizontal space.

Common Pitfalls

  • Creating a colorbar without attaching it to the intended axes.
  • Trying to fix a subplot layout issue only with fraction tweaks.
  • Forgetting that multi-axes figures need explicit colorbar ownership.
  • Judging colorbar mismatch before setting the final plot aspect ratio.
  • Relying on tight_layout alone to solve colorbar sizing problems.

Summary

  • Start by attaching the colorbar to the correct axes with fig.colorbar(..., ax=ax).
  • Use fraction and pad for small visual adjustments.
  • For precise sizing, create a dedicated colorbar axes with make_axes_locatable.
  • Treat multi-subplot figures as an explicit layout problem, not a default-behavior problem.
  • Finalize plot aspect before deciding whether the colorbar height truly matches the graph.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design