27

When I plot a matrix with a colorbar, then the colorbar has 10 ticks. Since the colorbar has to be pretty small, the ticklabels overlap. Therefore I want to reduce the number of ticks from 10 to 5. I do not want to reduce the font size!

Is there an easy way to do this? I do not want to set the ticks manually...

Sam
  • 7,252
  • 16
  • 46
  • 65
FrankTheTank
  • 1,579
  • 4
  • 14
  • 19

2 Answers2

50

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()
Bonlenfum
  • 19,101
  • 2
  • 53
  • 56
  • Thank you very much! This was the correct (and very easy) solution! – FrankTheTank Feb 25 '14 at 12:27
  • 3
    At the moment there is no tick at the upper end of the colorbar, but at the lower end. This looks very asymmetric and ugly to me. Is there a solution for that? – FrankTheTank Feb 28 '14 at 09:27
  • 3
    Ok.... just put cb.ax.yaxis.set_major_locator(matplotlib.ticker.AutoLocator()) before c.b.update_icks() – FrankTheTank Feb 28 '14 at 09:41
  • 4
    Thanks @FrankTheTank for the addition. For other people copy and pasting that addition, there's a hidden character which causes a `SyntaxError: invalid syntax` on the brackets. Just delete and retype the brackets (and thus deleting also the hidden character) and it'll work fine. – mjp Jan 17 '17 at 15:25
  • 1
    A simpler option to get ticks at both boundaries is: `LinearLocator(5)` – Oscillon Sep 23 '19 at 00:23
  • @FrankTheTank For adding ticks at the top of the colorbar, see [this post](https://stackoverflow.com/q/37161022/2005415). – Jason Dec 24 '19 at 01:47
13

For the record, this is now possible also via:

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

which talks to ticker.MaxNLocator.

ezatterin
  • 626
  • 5
  • 17