- Set the colorbar format during creation, by passing
matplotlib.ticker.FormatStrFormatterto theformat=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- Set the colorbar format during creation, by passing
matplotlib.ticker.FormatStrFormatterto theformat=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)
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()

Try
bounds = ['0.001','0.01','0.1','1','5','10','25','50']
cbar.set_ticklabels(bounds)
It's hard to test, since your example isn't directly runnable, but you should just be able to set the labels to whatever string you like. Something like so:
bound_labels = [str(v) if v <=1 else str(int(v)) for v in bounds]
cbar.set_ticklabels(bound_labels)
You could use colorbar's format parameter:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.ticker as ticker
img = np.random.randn(300,300)
myplot = plt.imshow(img)
def fmt(x, pos):
a, b = '{:.2e}'.format(x).split('e')
b = int(b)
return r'
'.format(a, b)
plt.colorbar(myplot, format=ticker.FuncFormatter(fmt))
plt.show()

You can specify the format of the colorbar ticks as follows:
pl.colorbar(myplot, format='%.0e')
A better solution is
from matplotlib.ticker import FuncFormatter
fmt = lambda x, pos: '{:.1%}'.format(x)
cbar = plt.colorbar(format=FuncFormatter(fmt))
One option is to just format the ticklabels manually. There is probably a better way but this usually works for me.
cbar.ax.set_yticklabels(['{:.0f}'.format(x) for x in np.arange(cbar_min, cbar_max+cbar_step, cbar_step)], fontsize=16, weight='bold')
Edit:
If you don't want to figure out the ticks yourself you can use:
for l in cbar.ax.yaxis.get_ticklabels():
l.set_weight("bold")
l.set_fontsize(16)
You may need to call draw() if they are not properly updated. This can be reduced to a one liner with:
setp(cbar.ax.yaxis.get_ticklabels(), weight='bold', fontsize=16)
Update the ticks and the tick labels:
cbar.set_ticks([mn,md,mx])
cbar.set_ticklabels([mn,md,mx])
A working example (for any value range) with five ticks along the bar is:
m0=int(np.floor(field.min())) # colorbar min value
m4=int(np.ceil(field.max())) # colorbar max value
m1=int(1*(m4-m0)/4.0 + m0) # colorbar mid value 1
m2=int(2*(m4-m0)/4.0 + m0) # colorbar mid value 2
m3=int(3*(m4-m0)/4.0 + m0) # colorbar mid value 3
cbar.set_ticks([m0,m1,m2,m3,m4])
cbar.set_ticklabels([m0,m1,m2,m3,m4])