Customized Colorbars Tutorial — Matplotlib 3.8.4 Documentation
Customized Colorbars Tutorial — Matplotlib 3.8.4 Documentation
4 documentation
A colorbar needs a "mappable" ( matplotlib.cm.ScalarMappable ) object (typically, an image) which indicates the colormap and
the norm to be used. In order to create a colorbar without an attached image, one can instead use a ScalarMappable with no
associated data.
The arguments to the colorbar call are the ScalarMappable (constructed using the norm and cmap arguments), the axes where
the colorbar should be drawn, and the colorbar's orientation.
cmap = mpl.cm.cool
norm = mpl.colors.Normalize(vmin=5, vmax=10)
fig.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=cmap),
cax=ax, orientation='horizontal', label='Some Units')
fig, ax = plt.subplots(layout='constrained')
https://matplotlib.org/stable/users/explain/colors/colorbar_only.html 1/4
19/04/2024 Customized Colorbars Tutorial — Matplotlib 3.8.4 documentation
cmap = mpl.cm.viridis
bounds = [-1, 2, 5, 7, 12, 15]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N, extend='both')
fig.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=cmap),
cax=ax, orientation='horizontal',
label="Discrete intervals with extend='both' keyword")
are colors). The "over" and "under" colors are set on the colormap using Colormap.with_extremes .
To display the out-of-range values on the colorbar, we use the extend argument in the colorbar() call. (This is equivalent to
passing the extend argument in the BoundaryNorm constructor as done in the previous example.)
To make the length of each colorbar segment proportional to its corresponding interval, we use the spacing argument in the
colorbar() call.
fig.colorbar(
mpl.cm.ScalarMappable(cmap=cmap, norm=norm),
cax=ax, orientation='horizontal',
extend='both',
spacing='proportional',
label='Discrete intervals, some other units',
)
fig.colorbar(
mpl.cm.ScalarMappable(cmap=cmap, norm=norm),
cax=ax, orientation='horizontal',
extend='both', extendfrac='auto',
spacing='uniform',
label='Custom extension lengths, some other units',
)
plt.show()
https://matplotlib.org/stable/users/explain/colors/colorbar_only.html 3/4
19/04/2024 Customized Colorbars Tutorial — Matplotlib 3.8.4 documentation
© Copyright 2002–2012 John Hunter, Darren Dale, Eric Firing, Michael Droettboom and the Matplotlib
development team; 2012–2024 The Matplotlib development team. Built with the PyData
Created using Sphinx 7.2.6. Sphinx Theme 0.13.3.
https://matplotlib.org/stable/users/explain/colors/colorbar_only.html 4/4