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 = np.clip(data, -1, 1) cax = ax.imshow(data, cmap='afmhot') ax.set_title('Gaussian noise with horizontal colorbar') # Add colorbar and adjust ticks afterwards cbar = fig.colorbar(cax, orientation='horizontal') cbar.set_ticks(ticks=[-1, 0, 1], labels=['Low', 'Medium', 'High']) 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()

🌐
TutorialsPoint
tutorialspoint.com › article › how-to-add-matplotlib-colorbar-ticks
How to add Matplotlib Colorbar Ticks?
March 25, 2026 - import numpy as np import matplotlib.pyplot as plt # Create sample data data = np.random.randn(10, 10) # Create the plot im = plt.imshow(data, cmap='viridis') # Define custom tick positions tick_positions = [-2, -1, 0, 1, 2] # Define custom tick labels tick_labels = ['Very Low', 'Low', 'Medium', 'High', 'Very High'] # Add colorbar with custom ticks and labels cb = plt.colorbar(im, ticks=tick_positions) cb.set_ticklabels(tick_labels) plt.title('Colorbar with Custom Tick Labels') plt.show()
🌐
Matplotlib
matplotlib.org › stable › api › colorbar_api.html
matplotlib.colorbar — Matplotlib 3.11.2 documentation
The location of the colorbar ticks. The ticklocation must match orientation. For example, a horizontal colorbar can only have ticks at the top or the bottom. If 'auto', the ticks will be the same as location, so a colorbar to the left will have ticks to the left.
🌐
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 ...
🌐
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 › 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()
Find elsewhere
🌐
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".
🌐
Matplotlib
matplotlib.org › 3.1.0 › api › colorbar_api.html
matplotlib.colorbar — Matplotlib 3.1.0 documentation
May 18, 2019 - Turns on the minor ticks on the colorbar without extruding into the "extend regions".
🌐
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.
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()

🌐
PyPI
pypi.org › project › matplotlib-colorbar
matplotlib-colorbar · PyPI
>>> import numpy as np >>> import matplotlib.pyplot as plt >>> import matplotlib.cbook as cbook >>> from matplotlib_colorbar.colorbar import Colorbar >>> plt.figure() >>> data = np.array(plt.imread(cbook.get_sample_data('grace_hopper.png'))) >>> mappable = plt.imshow(data[...,0], cmap='viridis') >>> colorbar = Colorbar(mappable, location='lower left') >>> colorbar.set_ticks([0.0, 0.5, 1.0]) >>> plt.gca().add_artist(colorbar) >>> plt.show()
🌐
GitHub
github.com › matplotlib › matplotlib › issues › 11937
Limiting ticks on colorbar axes falsify tick labels. · Issue #11937 · matplotlib/matplotlib
August 26, 2018 - Using locator_params(nbins=) on colorbar axes yield incorrect tick labels. If one has not checked data values this can quietly produce wrong figures. If this is an uncorrect usage of locator_params, is it possible to warn the user against that (docs, warming)? ... import numpy as np import matplotlib.pyplot as plt # simple contour plot with labels and colorbar cs = plt.contourf(np.arange(24).reshape(6, 4)) cs.clabel(colors='k', fmt='%.0f') cb = plt.colorbar(cs, label='cbar with wrong values') # reduce number of colorbar ticks # (this is the problematic line) cb.ax.locator_params(axis='y', nbins=6) plt.show()
Author: matplotlib
🌐
GeeksforGeeks
geeksforgeeks.org › rotation-of-colorbar-tick-labels-in-matplotlib
Rotation of colorbar tick labels in Matplotlib | GeeksforGeeks
January 24, 2021 - Colorbar is an axis that indicates the mapping of data values to the colors used in plot. The colorbar() function in pyplot module of matplotlib adds a colorbar to a plot indicating the color scale.
🌐
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 """ ... # 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 ...
🌐
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
🌐
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.