Update the ticks and the tick labels:

cbar.set_ticks([mn,md,mx])
cbar.set_ticklabels([mn,md,mx])
Answer from Eryk Sun on Stack Overflow
🌐
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 › 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')
🌐
Matplotlib
matplotlib.org › 3.5.1 › gallery › ticks › colorbar_tick_labelling_demo.html
Colorbar Tick Labelling — Matplotlib 3.5.1 documentation
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()
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-add-matplotlib-colorbar-ticks
How to add Matplotlib Colorbar Ticks?
March 25, 2026 - Use plt.colorbar(ticks=ticks) to specify custom tick positions. Combine with set_ticklabels() for custom labels and tick_params() for styling control.
🌐
LabEx
labex.io › tutorials › creating-custom-colorbar-tickels-in-matplotlib-48609
Customizing Matplotlib Colorbar Ticks | LabEx
In this lab, we learned how to customize the tick labels on a colorbar in Matplotlib. We first created a plot with a vertical colorbar and customized the tick labels using set_yticklabels. We then created a plot with a horizontal colorbar and customized the tick labels using set_xticklabels.
🌐
Matplotlib
matplotlib.org › stable › api › colorbar_api.html
matplotlib.colorbar — Matplotlib 3.11.2 documentation
Alternatively, this method can also be called with the signature colorbar.add_lines(contour_set, erase=True), in which case levels, colors, and linewidths are taken from contour_set. ... Major tick label Formatter for the colorbar.
🌐
GeeksforGeeks
geeksforgeeks.org › data visualization › setting-the-number-of-ticks-in-pltcolorbar-in-matplotlib
Setting the Number of Ticks in plt.colorbar in Matplotlib? - GeeksforGeeks
July 23, 2025 - Setting the number of ticks in plt.colorbar in Matplotlib means specifying the positions and labels of the discrete values displayed on the colorbar. This helps to control how the data range is visually represented, making it easier to interpret ...
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)
Find elsewhere
Top answer
1 of 2
6

You can keep the same locators as proposed by the colorbar function but change the ticklabels in order to print the formatted date as follows:

# change colobar ticks labels and locators 
cbar.set_ticks([s.colorbar.vmin + t*(s.colorbar.vmax-s.colorbar.vmin) for t in cbar.ax.get_yticks()])
cbar.set_ticklabels([mdates.datetime.datetime.fromtimestamp((s.colorbar.vmin + t*(s.colorbar.vmax-s.colorbar.vmin))/1000000000).strftime('%c') for t in cbar.ax.get_yticks()])
plt.show()

which gives the result below:

If you really want to control tick locations, you can compute the desired values (here for approximately 3 months intervals ~91.25 days):

i,ticks = 0,[s.colorbar.vmin]
while ticks[-1] < s.colorbar.vmax:
   ticks.append(s.colorbar.vmin+i*24*3600*91.25*1e9)
   i = i+1
ticks[-1] = s.colorbar.vmax
cbar.set_ticks(ticks)
cbar.set_ticklabels([mdates.datetime.datetime.fromtimestamp(t/1e9).strftime('%c') for t in ticks])
2 of 2
2

The colormapping machinery of matplotlib has no concepts of "units" like an x or y axis does, so you can do the conversion from date to floats manually before mapping and then set the locator and formatter manually. You can also look into how pandas maps their date object to floats, it may be a bit different than the native matplotlib mapping:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

dates = np.datetime64('2019-11-01') + np.arange(10)*np.timedelta64(1, 'D')
X= np.random.randn(10, 2)

plt.scatter(X[:, 0], X[:, 1], c=mdates.date2num(dates))
cb = plt.colorbar()
loc = mdates.AutoDateLocator()
cb.ax.yaxis.set_major_locator(loc)
cb.ax.yaxis.set_major_formatter(mdates.ConciseDateFormatter(loc))
plt.show()

Top answer
1 of 2
26

You are suffering from an off-by-one error. You have 10 ticklabels spread among 11 colors. You might be able to correct the error by using np.linspace instead of np.arange. Using np.linspace the third argument is the number of values desired. This reduces the amount of mental gymnastics needed to avoid the off-by-one error:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
import matplotlib.colors as mcolors

def colorbar_index(ncolors, cmap):
    cmap = cmap_discretize(cmap, ncolors)
    mappable = cm.ScalarMappable(cmap=cmap)
    mappable.set_array([])
    mappable.set_clim(-0.5, ncolors+0.5)
    colorbar = plt.colorbar(mappable)
    colorbar.set_ticks(np.linspace(0, ncolors, ncolors))
    colorbar.set_ticklabels(range(ncolors))

def cmap_discretize(cmap, N):
    """Return a discrete colormap from the continuous colormap cmap.

        cmap: colormap instance, eg. cm.jet. 
        N: number of colors.

    Example
        x = resize(arange(100), (5,100))
        djet = cmap_discretize(cm.jet, 5)
        imshow(x, cmap=djet)
    """

    if type(cmap) == str:
        cmap = plt.get_cmap(cmap)
    colors_i = np.concatenate((np.linspace(0, 1., N), (0.,0.,0.,0.)))
    colors_rgba = cmap(colors_i)
    indices = np.linspace(0, 1., N+1)
    cdict = {}
    for ki,key in enumerate(('red','green','blue')):
        cdict[key] = [ (indices[i], colors_rgba[i-1,ki], colors_rgba[i,ki])
                       for i in xrange(N+1) ]
    # Return colormap object.
    return mcolors.LinearSegmentedColormap(cmap.name + "_%d"%N, cdict, 1024)

fig, ax = plt.subplots()
A = np.random.random((10,10))*10
cmap = plt.get_cmap('YlGnBu')
ax.imshow(A, interpolation='nearest', cmap=cmap)
colorbar_index(ncolors=11, cmap=cmap)    
plt.show()

2 of 2
19

You can control the placement and the labels by hand. I'll start with a linear cmap generated from cmap_discretize on the page you linked:

import numpy as np
import pylab as plt

# The number of divisions of the cmap we have
k = 10

# Random test data
A = np.random.random((10,10))*k
c = cmap_discretize('jet', k)

# First show without
plt.subplot(121)
plt.imshow(A,interpolation='nearest',cmap=c)
plt.colorbar()

# Now label properly
plt.subplot(122)
plt.imshow(A,interpolation='nearest',cmap=c)

cb = plt.colorbar()
labels = np.arange(0,k,1)
loc    = labels + .5
cb.set_ticks(loc)
cb.set_ticklabels(labels)

plt.show()

🌐
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.1.1 › api › colorbar_api.html
matplotlib.colorbar — Matplotlib 3.1.2 documentation
Turns on the minor ticks on the colorbar without extruding into the "extend regions". ... Label the long axis of the colorbar.
🌐
TutorialsPoint
tutorialspoint.com › matplotlib › matplotlib_colorbars.htm
Matplotlib - Colorbars
import numpy as np from matplotlib import pyplot as plt # Adjust figure size and autolayout plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True # Generate random data data = np.random.randn(4, 4) # Plot the data with imshow im = plt.imshow(data, interpolation='nearest', cmap="PuBuGn") # Add colorbar and adjust its position # Decrease colorbar width and shift position to the right clb = plt.colorbar(im, shrink=0.9, pad=0.05) # Set the top label for colorbar clb.ax.set_title('Color Bar Title') # Customize color of ticks clb.ax.set_yticks([0, 1.5, 3, 4.5], labels=["A", "B", "C", "D"]) # Change color and font size of ticks clb.ax.tick_params(labelcolor='red', labelsize=20) plt.show()
🌐
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
"""Produce custom labelling for a colorbar. 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 orie
🌐
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.
🌐
GeeksforGeeks
geeksforgeeks.org › rotation-of-colorbar-tick-labels-in-matplotlib
Rotation of colorbar tick labels in Matplotlib | GeeksforGeeks
January 24, 2021 - The colorbar() function in pyplot module of matplotlib adds a colorbar to a plot indicating the color scale. ... Sometimes it is desirable to rotate the ticklabels for better visualization and understanding.
🌐
GitHub
github.com › matplotlib › matplotlib › issues › 15756
Incorrect tick labels on colorbar · Issue #15756 · matplotlib/matplotlib
November 22, 2019 - import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import matplotlib.cm import matplotlib.colors from matplotlib import ticker import numpy as np import random def hexbin_plot(x, y, png_file_name): def _get_ticks(vmin, vmax): vmin, vmax = 10**vmin, 10**vmax ticks = [] for n in [100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000]: if vmin <= n <= vmax: ticks.append(n) return ticks CMAP = "rainbow" assert len(x) == len(y) x = np.log10(x) y = np.log10(y) bins = "log" # this is the colormap scaling, not the x/y fig = plt.figure(figsize=(9,12)) axes = fig.add_subplot(
Author: matplotlib
🌐
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 2: In this Example, we are changing the label size in Plotly Express with the help of method im.figure.axes[0].tick_params(axis="x", labelsize=18), by passing the parameter axis value as x and label size as 18. ... # 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 tick label size of colorbar im.figure.axes[1].tick_params(axis="x", labelsize=18) plt.show()