• Set the colorbar format during creation, by passing matplotlib.ticker.FormatStrFormatter to the format= parameter.
import matplotlib.ticker as tkr
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(2023)
z = (np.random.random((10,10))*0.35+0.735)*1.e-7

fig, ax = plt.subplots(figsize=(10, 7))

p1 = ax.contourf(z, levels=np.linspace(0.735e-7, 1.145e-7, 10))

# compare the formats of the two colorbars
cb1 = fig.colorbar(p1, format=tkr.FormatStrFormatter('%.9f'))
cb1.set_label('%.9f', labelpad=-40, y=1.05, rotation=0)

cb2 = fig.colorbar(p1, format=tkr.FormatStrFormatter('%.2g'))
cb2.set_label('%.2g', labelpad=-40, y=1.05, rotation=0)

  • The colorbar can also be formatted after creation.
cb1 = fig.colorbar(p1)
cb1.ax.yaxis.set_major_formatter(tkr.FormatStrFormatter('%.9f'))
cb1.set_label('%.2g', labelpad=-40, y=1.05, rotation=0)
Answer from Ramendra 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.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
Top answer
1 of 2
5
  • Set the colorbar format during creation, by passing matplotlib.ticker.FormatStrFormatter to the format= parameter.
import matplotlib.ticker as tkr
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(2023)
z = (np.random.random((10,10))*0.35+0.735)*1.e-7

fig, ax = plt.subplots(figsize=(10, 7))

p1 = ax.contourf(z, levels=np.linspace(0.735e-7, 1.145e-7, 10))

# compare the formats of the two colorbars
cb1 = fig.colorbar(p1, format=tkr.FormatStrFormatter('%.9f'))
cb1.set_label('%.9f', labelpad=-40, y=1.05, rotation=0)

cb2 = fig.colorbar(p1, format=tkr.FormatStrFormatter('%.2g'))
cb2.set_label('%.2g', labelpad=-40, y=1.05, rotation=0)

  • The colorbar can also be formatted after creation.
cb1 = fig.colorbar(p1)
cb1.ax.yaxis.set_major_formatter(tkr.FormatStrFormatter('%.9f'))
cb1.set_label('%.2g', labelpad=-40, y=1.05, rotation=0)
2 of 2
2

The problem is that while the FormatStrFormatter allows to set the format precisely, it is not capable of handling offsets like the 1e-7 in the case from the question.

On the other hand the default ScalarFormatter automatically selects its own format, without letting the user change it. While this is mostly desireable, in this case, we want to specify the format ourself.

A solution is to subclass the ScalarFormatter and reimplement its ._set_format() method, similar to this answer.

Note that you would want "%.2f" instead of "%.2g" to always show 2 digits after the decimal point.

import numpy as np; np.random.seed(0)
import matplotlib.pyplot as plt
import matplotlib.ticker

class FormatScalarFormatter(matplotlib.ticker.ScalarFormatter):
    def __init__(self, fformat="%1.1f", offset=True, mathText=True):
        self.fformat = fformat
        matplotlib.ticker.ScalarFormatter.__init__(self,useOffset=offset,
                                                        useMathText=mathText)
    def _set_format(self, vmin, vmax):
        self.format = self.fformat
        if self._useMathText:
            self.format = '' % matplotlib.ticker._mathdefault(self.format)

z = (np.random.random((10,10))*0.35+0.735)*1.e-7

fig, ax = plt.subplots()
plot = ax.contourf(z, levels=np.linspace(0.735e-7,1.145e-7,10))

fmt = FormatScalarFormatter("%.2f")

cbar = fig.colorbar(plot,format=fmt)

plt.show()

๐ŸŒ
MathWorks
mathworks.com โ€บ matlabcentral โ€บ answers โ€บ 1818910-how-to-properly-set-ticks-numbers-and-the-their-decimal-places-on-colorbar
How to properly set ticks, numbers and the their decimal places on colorbar? - MATLAB Answers - MATLAB Central
October 6, 2022 - Alternatively, you can modify your example by setting 50 ticks and displaying only 10 or 11 values on the colorbar. ... https://www.mathworks.com/matlabcentral/answers/1818910-how-to-properly-set-ticks-numbers-and-the-their-decimal-places-on-colorbar#comment_2400300
๐ŸŒ
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()
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ setting-the-number-of-ticks-in-pltcolorbar-in-matplotlib
Setting the Number of Ticks in plt.colorbar in Matplotlib? - GeeksforGeeks
August 8, 2024 - 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 the color-coded information.
Find elsewhere
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 63086610 โ€บ re-format-colorbar-tick-labels-from-standard-form-to-decimal
python - Re-format colorbar tick labels from standard form to decimal - Stack Overflow
July 25, 2020 - How can I re-format the tick labels on my colorbar such that they are not in standard form. I would like the labels to read 0.02, 0.03, 0.04 ..., 0.2, NOT 2 x 10^-2, 3 x 10^-2 etc, whilst retaining the logarithmic scale. See image below for the current image. #Gf import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import interp2d from mpl_toolkits.axes_grid1 import make_axes_locatable from astropy.visualization import simple_norm from matplotlib.colors import LogNorm from matplotlib.ticker import LogFormatter x_list = np.array([x * 3 for x in X_COORDINATE]) z_list = np.ar
๐ŸŒ
Matplotlib
discourse.matplotlib.org โ€บ community โ€บ matplotlib-users
FuncFormatter and Colorbar - matplotlib-users - Matplotlib
January 9, 2008 - Hi to all! I have a question concerning reformatting of axis-ticks via the FuncFormatter-class. In german, itโ€™s common to use a comma as separator for decimal numbers instead of a dot. To realize it in matplotlib, I do something like from matplotlib.ticker import FuncFormatter import pylab pylab.figure() formatter = FuncFormatter(lambda x,pos: ("%.2f"%x).replace(".",",")) ax = pylab.axes() ax.xaxis.set_major_formatter (formatter) ax.yaxis.set_major_formatter(formatter) ax.plot(pylab.ar...
๐ŸŒ
Matplotlib
matplotlib.org โ€บ stable โ€บ api โ€บ colorbar_api.html
matplotlib.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.
๐ŸŒ
Matplotlib
matplotlib.org โ€บ 3.3.3 โ€บ gallery โ€บ ticks_and_spines โ€บ colorbar_tick_labelling_demo.html
Colorbar Tick Labelling Demo โ€” Matplotlib 3.3.3 documentation
November 12, 2020 - fig, ax = plt.subplots() data = np.clip(randn(250, 250), -1, 1) cax = ax.imshow(data, 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
๐ŸŒ
pythontutorials
pythontutorials.net โ€บ blog โ€บ how-to-add-matplotlib-colorbar-ticks
How to Add Matplotlib Colorbar Ticks and Set yticklabels (with LogNorm Example Code) โ€” pythontutorials.net
It acts as a key, helping viewers interpret what each color represents. For example, in a heatmap, the colorbar might range from blue (low values) to red (high values), with ticks indicating specific numerical thresholds. By default, Matplotlib generates colorbar ticks and labels automatically based on the data range.
๐ŸŒ
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.
๐ŸŒ
Matplotlib
matplotlib.org โ€บ 3.1.0 โ€บ gallery โ€บ ticks_and_spines โ€บ colorbar_tick_labelling_demo.html
Colorbar Tick Labelling Demo โ€” Matplotlib 3.1.0 documentation
January 5, 2020 - 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
๐ŸŒ
Matplotlib
matplotlib.org โ€บ stable โ€บ api โ€บ ticker_api.html
matplotlib.ticker โ€” Matplotlib 3.11.2 documentation
The number of decimal places to place after the point. If None (the default), the number will be computed automatically. ... A string that will be appended to the label. It may be None or empty to indicate that no symbol should be used. LaTeX special characters are escaped in symbol whenever ...