Matplotlib colorbar shows only up to half the tick values

Viewed 1784

When creating colorbars using the "ColorbarBase" object and adding ticks with the "set_yticklabels" method matplotlib only displays up to half the values specified in the "ticks" list. This only started happening after I upgraded to the latest matplotlib version.

Here is a short code to test it:

    import matplotlib.pyplot as plt
    import matplotlib as mpl
    fig = plt.figure(1)
    cax = fig.add_axes([0.8, 0.15, 0.03, 0.72])
    ticks = range(11)
    cbar = mpl.colorbar.ColorbarBase(cax, cmap='rainbow', orientation='vertical')
    cbar.ax.set_yticklabels(ticks)
    plt.show()

Using matplotlib version 2.1.0 I get a colorbar with ticks that go from 1 to 5, meanwhile with matplotlib version 1.4.3 I get the correct figure with ticks that go from 1 to 10.

I can do a dirty fix by increasing the tick range by two, but I would prefer this not to happen. Any tips on what could be going on?

1 Answers

I would think that the above code works in matplotlib 1.4 is only coincidence. The point is that you do not tell the colorbar what range it should cover. It would hence cover the range 0 - 1. In matplotlib versions below 2, an axes with range 0 - 1 would have 11 tickmarks (0,0.1,0.2,...); then setting the labels as the range(11) would fit well (0 stays 0, 0.1 is labeled 1, etc.). In newer matplotlib versions the labeling density is by default lower (0,0.2,0.4,...). Hence you only get the label up to 5 (0 stays 0, 0.2 is labeled 1, 0.4 is labeled 2, etc. up to 5). At the end this approach is anyways very fragile, since the tick density is also subject to the size of the axes and might change.

So you would want to tell the colorbar which range it should cover. One way to do that would be to supply a norm.

ticks = range(11)
cbar = mpl.colorbar.ColorbarBase(cax, cmap='rainbow', orientation='vertical', 
                                 norm=plt.Normalize(ticks[0],ticks[-1]))

You can then set the ticks and ticklabels to the numbers within ticks.

cbar.set_ticks(ticks)
cbar.ax.set_yticklabels(ticks)

Complete example:

import matplotlib.pyplot as plt
import matplotlib as mpl
fig = plt.figure(1)
cax = fig.add_axes([0.8, 0.15, 0.03, 0.72])
ticks = range(11)
cbar = mpl.colorbar.ColorbarBase(cax, cmap='rainbow', orientation='vertical', 
                                 norm=plt.Normalize(ticks[0],ticks[-1]))
cbar.set_ticks(ticks)
cbar.ax.set_yticklabels(ticks)
plt.show()

enter image description here

Related