A better solution is
from matplotlib.ticker import FuncFormatter
fmt = lambda x, pos: '{:.1%}'.format(x)
cbar = plt.colorbar(format=FuncFormatter(fmt))
Answer from Gen on Stack OverflowA 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])
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])
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()

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()

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()


