import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap

#discrete color scheme
cMap = ListedColormap(['white', 'green', 'blue','red'])

#data
np.random.seed(42)
data = np.random.rand(4, 4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=cMap)

#legend
cbar = plt.colorbar(heatmap)

cbar.ax.get_yaxis().set_ticks([])
for j, lab in enumerate(['$0$','$1$','$2$','$>3$']):
    cbar.ax.text(.5, (2 * j + 1) / 8.0, lab, ha='center', va='center')
cbar.ax.get_yaxis().labelpad = 15
cbar.ax.set_ylabel('# of contacts', rotation=270)


# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)
ax.invert_yaxis()

#labels
column_labels = list('ABCD')
row_labels = list('WXYZ')
ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)

plt.show()

You were very close. Once you have a reference to the color bar axis, you can do what ever you want to it, including putting text labels in the middle. You might want to play with the formatting to make it more visible.

Answer from tacaswell on Stack Overflow
🌐
Matplotlib
matplotlib.org › stable › api › _as_gen › matplotlib.pyplot.colorbar.html
matplotlib.pyplot.colorbar — Matplotlib 3.11.2 documentation
If False the minimum and maximum colorbar extensions will be triangular (the default). If True the extensions will be rectangular. ... If None, ticks are determined automatically from the input. ... If None, ScalarFormatter is used. Format strings, e.g., "%4.2e" or "{x:.2e}", are supported. An alternative Formatter may be given instead. ... Whether to draw lines at color boundaries. ... The label on the colorbar's long axis.
Top answer
1 of 4
194
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap

#discrete color scheme
cMap = ListedColormap(['white', 'green', 'blue','red'])

#data
np.random.seed(42)
data = np.random.rand(4, 4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=cMap)

#legend
cbar = plt.colorbar(heatmap)

cbar.ax.get_yaxis().set_ticks([])
for j, lab in enumerate(['$0$','$1$','$2$','$>3$']):
    cbar.ax.text(.5, (2 * j + 1) / 8.0, lab, ha='center', va='center')
cbar.ax.get_yaxis().labelpad = 15
cbar.ax.set_ylabel('# of contacts', rotation=270)


# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)
ax.invert_yaxis()

#labels
column_labels = list('ABCD')
row_labels = list('WXYZ')
ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)

plt.show()

You were very close. Once you have a reference to the color bar axis, you can do what ever you want to it, including putting text labels in the middle. You might want to play with the formatting to make it more visible.

2 of 4
9

This will make you add label and change colorbar's tick and label size:

clb=plt.colorbar()
clb.ax.tick_params(labelsize=8) 
clb.ax.set_title('Your Label',fontsize=8)

This can be also used if you have sublots:

plt.tight_layout()
plt.subplots_adjust(bottom=0.05)
cax = plt.axes([0.1, 0, 0.8, 0.01]) #Left,bottom, length, width
clb=plt.colorbar(cax=cax,orientation="horizontal")
clb.ax.tick_params(labelsize=8) 
clb.ax.set_title('Your Label',fontsize=8)
🌐
Matplotlib
matplotlib.org › stable › api › colorbar_api.html
matplotlib.colorbar — Matplotlib 3.11.2 documentation
In order to draw a colorbar not associated with other elements in the figure, e.g. when showing a colormap by itself, one can create an empty ColorizingArtist, or directly pass cmap and norm instead of mappable to Colorbar. Useful public methods are set_label() and add_lines().
🌐
Readthedocs
proplot.readthedocs.io › en › latest › colorbars_legends.html
Colorbars and legends — ProPlot documentation
Notable features include “inset” colorbars, “outer” legends, on-the-fly colorbars and legends, colorbars built from artists, and row-major and centered-row legends. Matplotlib supports drawing “inset” legends and “outer” colorbars using the loc and location keyword arguments.
🌐
GitHub
github.com › pydata › xarray › issues › 3275
Change the label size and tick label size of colorbar · Issue #3275 · pydata/xarray
September 2, 2019 - Still don't know how to decouple the axis tick size from colorbar tick size. here is the code: import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt · mpl.rcParams['xtick.labelsize'] = 20 mpl.rcParams['ytick.labelsize'] = 20 a=np.random.rand(10,10) im=plt.imshow(a) cb=plt.colorbar(im,orientation='horizontal').set_label(label='Label',size=20,weight='bold') plt.show()
🌐
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()
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › matplotlib-pyplot-colorbar-function-in-python
Matplotlib.pyplot.colorbar() function in Python - GeeksforGeeks
July 23, 2025 - The tick labels on the colorbar are adjusted for better readability using tick_params(). Example 4: This example shows how to change the orientation of a colorbar from vertical to horizontal for better layout flexibility.
🌐
Matplotlib
matplotlib.org › stable › gallery › ticks › colorbar_tick_labelling_demo.html
Colorbar Tick labelling — Matplotlib 3.11.2 documentation
fig, ax = plt.subplots() data = rng.standard_normal((250, 250)) cax = ax.imshow(data, vmin=-1, vmax=1, cmap='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], format=mticker.FixedFormatter(['< -1', '0', '> 1']), extend='both' ) labels = cbar.ax.get_yticklabels() labels[0].set_verticalalignment('top') labels[-1].set_verticalalignment('bottom')
🌐
GitHub
github.com › matplotlib › matplotlib › issues › 6471
Colorbar label position different when executing a block of code · Issue #6471 · matplotlib/matplotlib
May 24, 2016 - Now, when working interactively in the QtConsole, if I run all of the above code _except_ the last line, let the figure window render, then execute that last line mycolorbar( ax, cbar) on its own, I get the "correct" position for the colorbar label.
Author: matplotlib
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-change-colorbar-labels-in-matplotlib
How to change colorbar labels in matplotlib ? - GeeksforGeeks
July 23, 2025 - To change the label's font size we will use ax.tick_params() methods which increase the font of the labels. ... # Python Program illustrating # pyplot.colorbar() method import numpy as np import matplotlib.pyplot as plt # Dataset # List of total number of items purchased # from each products purchaseCount = [100, 200, 150, 23, 30, 50, 156, 32, 67, 89] # List of total likes of 10 products likes = [50, 70, 100, 10, 10, 34, 56, 18, 35, 45] # List of Like/Dislike ratio of 10 products ratio = [1, 0.53, 2, 0.76, 0.5, 2.125, 0.56, 1.28, 1.09, 1.02] # scatterplot plt.scatter(x=purchaseCount, y=likes, c=ratio, cmap="summer") plt.colorbar().ax.tick_params(labelsize=10) plt.show()
🌐
YouTube
youtube.com › watch
Matplotlib Colorbar Explained: From Basics to Advanced Styling - YouTube
Colorbar, Pyplot colorbar function, and Figure colorbar function are the topics that I have explained in this tutorial.======================================...
Published: June 18, 2025
🌐
PyPI
pypi.org › project › matplotlib-colorbar
matplotlib-colorbar · PyPI
Here are parameters of the Colorbar class constructor. mappable: scalar mappable object which implements the methods get_cmap and get_array (default: None, the mappable can be specified later) label: label on top of the color bar (default: None, ...
🌐
GeeksforGeeks
geeksforgeeks.org › data visualization › how-to-change-the-font-size-of-colorbars-in-matplotlib-1
How to Change the Font Size of Colorbars in Matplotlib - GeeksforGeeks
July 23, 2025 - Fine-tuning: The tick_params method offers various parameters to customize the appearance of ticks and labels, such as colors, width, and length. Subplots: If you are working with multiple subplots, ensure each subplot’s colorbar is adjusted individually for consistent presentation.
🌐
Python Data Science Handbook
jakevdp.github.io › PythonDataScienceHandbook › 04.07-customizing-colorbars.html
Customizing Colorbars | Python Data Science Handbook
Plot legends identify discrete labels of discrete points. For continuous labels based on the color of points, lines, or regions, a labeled colorbar can be a great tool. In Matplotlib, a colorbar is a separate axes that can provide a key for the meaning of colors in a plot.
🌐
TutorialsPoint
tutorialspoint.com › article › top-label-for-matplotlib-colorbars
Top label for Matplotlib colorbars
May 6, 2021 - To place a top label for colorbars, we can use colorbar's axis to set the title.
🌐
GeeksforGeeks
geeksforgeeks.org › python › change-the-label-size-and-tick-label-size-of-colorbar-using-matplotlib-in-python
Change the label size and tick label size of colorbar using Matplotlib in Python - GeeksforGeeks
November 5, 2021 - Example 1: In this example, we are changing the label size in Plotly Express with the help of method im.figure.axes[0].tick_params(axis="both", labelsize=21), by passing the parameters axis value as both axis and label size as 21. ... # importing libraries import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt # setup data a = np.random.rand(10, 10) im = plt.imshow(a, cmap="bwr") cb = plt.colorbar(im, orientation='horizontal') # change the label size im.figure.axes[0].tick_params(axis="both", labelsize=21) plt.show()
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-give-matplolib-imshow-plot-colorbars-a-label
How to give Matplolib imshow plot colorbars a label?
March 26, 2026 - To add a label to a matplotlib imshow() plot colorbar, you can use the set_label() method on the colorbar object.