How to set number of ticks in plt.colorbar?

The MaxNLocator ticker might suit your purposes?

class matplotlib.ticker.MaxNLocator

Select no more than N intervals at nice locations

For example:

from matplotlib import ticker

# (generate plot here)
cb = plt.colorbar()
tick_locator = ticker.MaxNLocator(nbins=5)
cb.locator = tick_locator
cb.update_ticks()
plt.show()

For the record, this is now possible also via:

cbar = plt.colorbar()
cbar.ax.locator_params(nbins=5)

which talks to ticker.MaxNLocator.