pythonmatplotlibcolorbar

How to set number of ticks in plt.colorbar?


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...


Solution

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