Colour schemes are defined in the range 0 to 1, therefore you first need to normalise your values (0 to 5) to the range 0 to 1. Then you can pull the colour from the colormap. At the end you have to plot a color bar using the colour map and norm that you chose on the axis you used for plotting.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm, colors


def func(x, a):
    return np.exp(-x * a)


x = np.linspace(0, 5)

fig, ax = plt.subplots()

# define color map
cmap = cm.get_cmap("Spectral")

# need to normalize because color maps are defined in [0, 1]
norm = colors.Normalize(0, 5)

for a in range(1, 5):
    ax.plot(x, func(x, a), 
        color=cmap(norm(a)))  # get color from color map 

# plot colorbar
fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax)

plt.show()

The plot looks like this:

Answer from Johannes Heuel on Stack Overflow
๐ŸŒ
Matplotlib
matplotlib.org โ€บ stable โ€บ users โ€บ explain โ€บ colors โ€บ colorbar_only.html
Customized Colorbars Tutorial โ€” Matplotlib 3.11.2 documentation
The following example shows how to make a discrete colorbar based on a continuous cmap. We use matplotlib.colors.BoundaryNorm to describe the interval boundaries (which must be in increasing order), and further pass the extend argument to it to further display "over" and "under" colors (which ...
People also ask

How do I control colorbar size and placement?
Use layout arguments such as location, shrink, aspect, and fraction, and give Matplotlib the relevant axes for space allocation.
๐ŸŒ
pythonpool.com
pythonpool.com โ€บ home โ€บ matplotlib โ€บ matplotlib colorbar: cmap, norm, labels, and layout
Matplotlib Colorbar Explained with Examples - Python Pool
How do I make colorbars comparable across plots?
Reuse the same normalization range and colormap policy for each mappable instead of allowing each plot to choose a different scale.
๐ŸŒ
pythonpool.com
pythonpool.com โ€บ home โ€บ matplotlib โ€บ matplotlib colorbar: cmap, norm, labels, and layout
Matplotlib Colorbar Explained with Examples - Python Pool
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ matplotlib โ€บ matplotlib_colorbars.htm
Matplotlib - Colorbars
Here is another example creates a simple colorbar for the plot using the pyplot.colorbar() function with default parameters. import matplotlib.pyplot as plt import numpy as np # Generate sample data data = np.random.random((10, 10)) # Create a plot with an image and a colorbar fig, ax = plt.subplots(figsize=(7,4)) im = ax.imshow(data, cmap='viridis') # Add a colorbar to the right of the image cbar = plt.colorbar(im, ax=ax) # Show the plot plt.show() print('Successfully drawn the colorbar...')
๐ŸŒ
Matplotlib
matplotlib.org โ€บ stable โ€บ users โ€บ explain โ€บ axes โ€บ colorbar_placement.html
Placing colorbars โ€” Matplotlib 3.11.2 documentation
The first column has the same type of data in both rows, so it may be desirable to have just one colorbar. We do this by passing Figure.colorbar a list of Axes with the ax kwarg.
๐ŸŒ
Matplotlib
matplotlib.org โ€บ stable โ€บ api โ€บ _as_gen โ€บ matplotlib.pyplot.colorbar.html
matplotlib.pyplot.colorbar โ€” Matplotlib 3.11.2 documentation
The location, relative to the parent Axes, where the colorbar Axes is created. It also determines the orientation of the colorbar (colorbars on the left and right are vertical, colorbars at the top and bottom are horizontal).
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ matplotlib-pyplot-colorbar-function-in-python
Matplotlib.pyplot.colorbar() function in Python - GeeksforGeeks
July 23, 2025 - Explanation: This example creates a scatter plot where the x-axis represents purchase counts and the y-axis represents likes. The color of each point corresponds to a "Like/Dislike Ratio," mapped using the summer colormap.
๐ŸŒ
Python Pool
pythonpool.com โ€บ home โ€บ matplotlib โ€บ matplotlib colorbar: cmap, norm, labels, and layout
Matplotlib Colorbar Explained with Examples - Python Pool
July 13, 2026 - That keeps scripts, tests, and documentation examples from leaving open windows or accumulating figures in memory. Before saving a final figure, check that colorbar labels and tick text are not clipped by the canvas edge. ... imshow() returns an image object. Pass that object to fig.colorbar() and attach the colorbar to the same axes. try: import numpy as np import matplotlib.pyplot as plt except ModuleNotFoundError: print("Install numpy and matplotlib to run this example.") else: data = np.arange(16).reshape(4, 4) fig, ax = plt.subplots() image = ax.imshow(data, cmap="viridis") colorbar = fig.colorbar(image, ax=ax) colorbar.set_label("value") ax.set_title("imshow colorbar") plt.close(fig)
Find elsewhere
๐ŸŒ
Matplotlib
matplotlib.org โ€บ 3.1.0 โ€บ gallery โ€บ color โ€บ colorbar_basics.html
Colorbar โ€” Matplotlib 3.1.0 documentation
May 18, 2019 - cbar = fig.colorbar(pos_neg_clipped, ax=ax3, extend='both') cbar.minorticks_on() plt.show() The use of the following functions, methods, classes and modules is shown in this example: import matplotlib import matplotlib.colorbar matplotlib.axes.Axes.imshow matplotlib.pyplot.imshow matplotlib.figure.Figure.colorbar matplotlib.pyplot.colorbar matplotlib.colorbar.Colorbar.minorticks_on matplotlib.colorbar.Colorbar.minorticks_off
๐ŸŒ
Python Data Science Handbook
jakevdp.github.io โ€บ PythonDataScienceHandbook โ€บ 04.07-customizing-colorbars.html
Customizing Colorbars | Python Data Science Handbook
Matplotlib allows for a large range of colorbar customization. The colorbar itself is simply an instance of plt.Axes, so all of the axes and tick formatting tricks we've learned are applicable. The colorbar has some interesting flexibility: for example, we can narrow the color limits and indicate the out-of-bounds values with a triangular arrow at the top and bottom by setting the extend property.
๐ŸŒ
Matplotlib
matplotlib.org โ€บ stable โ€บ api โ€บ colorbar_api.html
matplotlib.colorbar โ€” Matplotlib 3.11.2 documentation
Colorbars are typically created through Figure.colorbar or its pyplot wrapper pyplot.colorbar, which internally use Colorbar together with make_axes_gridspec (for GridSpec-positioned Axes) or make_axes (for non-GridSpec-positioned Axes). End-users most likely won't need to directly use this module's API. class matplotlib.colorbar.Colorbar(ax, mappable=None, *, alpha=None, location=None, extend=None, extendfrac=None, extendrect=False, ticks=None, format=None, values=None, boundaries=None, spacing='uniform', drawedges=False, label='', cmap=None, norm=None, orientation=None, ticklocation='auto')[source]#
๐ŸŒ
Matplotlib
matplotlib.org โ€บ 3.4.3 โ€บ gallery โ€บ ticks_and_spines โ€บ colorbar_tick_labelling_demo.html
Colorbar Tick Labelling โ€” Matplotlib 3.4.3 documentation
August 13, 2021 - fig, ax = plt.subplots() data = np.clip(randn(250, 250), -1, 1) cax = ax.imshow(data, cmap=cm.afmhot) ax.set_title('Gaussian noise with horizontal colorbar') cbar = fig.colorbar(cax, ticks=[-1, 0, 1], orientation='horizontal') cbar.ax.set_xticklabels(['Low', 'Medium', 'High']) # horizontal colorbar plt.show()
๐ŸŒ
Matplotlib
matplotlib.org โ€บ stable โ€บ tutorials โ€บ colors โ€บ colorbar_only.html
Customized Colorbars Tutorial โ€” Matplotlib 3.7.2 documentation
August 13, 2021 - A colorbar needs a "mappable" (matplotlib.cm.ScalarMappable) object (typically, an image) which indicates the colormap and the norm to be used.
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ matplotlib โ€บ add colorbar matplotlib
How to Show Colorbar in Matplotlib | Delft Stack
March 11, 2025 - Remember, a well-placed colorbar not only aids in interpretation but also adds an aesthetic touch to your visualizations. So go ahead and experiment with these techniques to elevate your data presentations! How do I change the colormap in Matplotlib? You can change the colormap by using the cmap parameter in plotting functions like imshow or contourf. For example, cmap='plasma' will apply the plasma colormap.
๐ŸŒ
Matplotlib
matplotlib.org โ€บ 3.3.4 โ€บ gallery โ€บ color โ€บ colorbar_basics.html
Colorbar โ€” Matplotlib 3.3.4 documentation
cbar = fig.colorbar(pos_neg_clipped, ax=ax3, extend='both') cbar.minorticks_on() plt.show() The use of the following functions, methods, classes and modules is shown in this example: import matplotlib import matplotlib.colorbar matplotlib.axes.Axes.imshow matplotlib.pyplot.imshow matplotlib.figure.Figure.colorbar matplotlib.pyplot.colorbar matplotlib.colorbar.Colorbar.minorticks_on matplotlib.colorbar.Colorbar.minorticks_off
๐ŸŒ
Matplotlib
matplotlib.org โ€บ 2.0.2 โ€บ examples โ€บ pylab_examples โ€บ colorbar_tick_labelling_demo.html
pylab_examples example code: colorbar_tick_labelling_demo.py โ€” Matplotlib 2.0.2 documentation
Contributed by Scott Sinclair """ import matplotlib.pyplot as plt import numpy as np from matplotlib import cm from numpy.random import randn # Make plot with vertical (default) colorbar fig, ax = plt.subplots() data = np.clip(randn(250, 250), -1, 1) cax = ax.imshow(data, interpolation='nearest', cmap=cm.coolwarm) ax.set_title('Gaussian noise with vertical colorbar') # Add colorbar, make sure to specify tick locations to match desired ticklabels cbar = fig.colorbar(cax, ticks=[-1, 0, 1]) cbar.ax.set_yticklabels(['< -1', '0', '> 1']) # vertically oriented colorbar # Make plot with horizontal co
๐ŸŒ
Matplotlib
matplotlib.org โ€บ 3.1.3 โ€บ tutorials โ€บ colors โ€บ colorbar_only.html
Customized Colorbars Tutorial โ€” Matplotlib 3.1.3 documentation
import matplotlib.pyplot as plt import matplotlib as mpl fig, ax = plt.subplots(figsize=(6, 1)) fig.subplots_adjust(bottom=0.5) cmap = mpl.cm.cool norm = mpl.colors.Normalize(vmin=5, vmax=10) cb1 = mpl.colorbar.ColorbarBase(ax, cmap=cmap, norm=norm, orientation='horizontal') cb1.set_label('Some Units') fig.show() The second example illustrates the use of a ListedColormap which generates a colormap from a set of listed colors, colors.BoundaryNorm() which generates a colormap index based on discrete intervals and extended ends to show the "over" and "under" value colors.
๐ŸŒ
Matplotlib
matplotlib.org โ€บ 3.1.0 โ€บ tutorials โ€บ colors โ€บ colorbar_only.html
Customized Colorbars Tutorial โ€” Matplotlib 3.1.0 documentation
May 18, 2019 - import matplotlib.pyplot as plt import matplotlib as mpl fig, ax = plt.subplots(figsize=(6, 1)) fig.subplots_adjust(bottom=0.5) cmap = mpl.cm.cool norm = mpl.colors.Normalize(vmin=5, vmax=10) cb1 = mpl.colorbar.ColorbarBase(ax, cmap=cmap, norm=norm, orientation='horizontal') cb1.set_label('Some Units') fig.show() The second example illustrates the use of a ListedColormap which generates a colormap from a set of listed colors, colors.BoundaryNorm() which generates a colormap index based on discrete intervals and extended ends to show the "over" and "under" value colors.
๐ŸŒ
Medium
medium.com โ€บ @yxs682 โ€บ add-color-bars-in-python-plt-matplotlib-pyplot-at-will-9a37ba142c59
Add color bars in python plt(matplotlib.pyplot) at will | by Yu-Hao Sun | Medium
October 26, 2022 - For the color gradient in the example, R ranges from 0 to 1, G is set fixed at 0.5, B is set to zero. ... import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap import matplotlib.cm as cm ... plt.figure() # start a figureN = 200 # The bigger N is, the more continuous the colorbar looksRG = np.ones((N, 4)) # N by 4 array for R, G, B, alphaRG[:, 0] = np.linspace(0, 1, N) # R spans from 0 to 1RG[:, 1] = 0.5*np.ones(N) # G = 0.5 fixedRG[:, 2] = np.zeros(N) # B = 0 fixed# The fourth component is alpha, which is 1 fixedRG_cmp = ListedColormap(RG) # create color map with N by 4 arraynorm = plt.Normalize(10, 19.9) # create the value scale for color bar# plot color bar:plt.colorbar(cm.ScalarMappable(norm=norm, cmap=RG_cmp))