colorbar() (Matplotlib)
fig.colorbar() adds a color-scale legend beside a plot, showing which colors of a colormap correspond to which data values. It is the key that makes a colored scatter, heatmap, or image readable.
Matplotlib
When color encodes a number, the viewer needs to know what each shade means — that is what a colorbar provides. You attach it to a mappable object (the return value of scatter, imshow, contourf, etc.): fig.colorbar(sc, ax=ax) draws the scale next to that plot.
Useful arguments include label to name the quantity, orientation='horizontal' to lay it flat, and shrink to size it relative to the Axes. In a multi-panel figure you point the colorbar at one or several Axes so Matplotlib carves out room for it.
Without a colorbar a colored plot is just decoration; with one the color channel becomes quantitative. It returns a Colorbar object you can further customize, such as setting custom ticks.
Syntax
fig.colorbar(mappable, ax=ax, label=None, orientation='vertical')Examples
Python
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
im = ax.imshow(np.arange(9).reshape(3, 3))
cb = fig.colorbar(im)
print(type(cb).__name__)Output:
Colorbar