Search code examples
pythonmatplotlibplotcolorbar

Matplotlib colorbar tick positioning - change between matplotlib versions?


Matplotlib seems to have changed the way minor colorbar ticks should be set. A minimal example is below. In matplotlib 2.2.3, that code creates 11 minor ticks between 0 and 10, in matplotlib 3.0.3 between 0 and 1. Is there any reference for this? I could not find anything in the changelogs.

import numpy as np
import matplotlib
import matplotlib.pyplot as plt

np.random.seed(1000)
im = plt.imshow(np.random.rand(10,10) * 10)
cbar = plt.colorbar()
plt.clim(0,10)
cax = cbar.ax
cax.yaxis.set_ticks(np.linspace(0,1,11),minor=True)

Solution

  • You are right, there has been a major change in colorbars in version 3, which unfortunately is not well communicated. It's somehow hidden in this What's new entry

    The ticks for colorbar now adjust for the size of the colorbar
    Colorbar ticks now adjust for the size of the colorbar if the colorbar is made from a mappable that is not a contour or doesn't have a BoundaryNorm, or boundaries are not specified. If boundaries, etc are specified, the colorbar maintains the original behavior.

    What this means is also that the colorbar is now scaled like any other axis. Meaning, if you want to have 11 ticks between 0 and 10, you will need to use

    ticks = np.linspace(0,10,11)
    cbar.ax.xaxis.set_ticks(ticks,minor=True)
    

    enter image description here