Search code examples
pythonmatplotlibcolorbar

Colorbar scientific notation offset


When plotting a colorbar, the top label (I guess this would be called the offset) is mis-centered. This didn't use to happen, I have examples of old code where it was centered above the colorbar, but I have no clue what has changed.

Example:

import numpy as np
import matplotlib.pyplot as plt

z = np.random.random((10,10))

fig, ax = plt.subplots()
im = ax.imshow(z)
cb = fig.colorbar(im)

cb.formatter.set_powerlimits((0, 0))
cb.update_ticks()

plt.show()

Gives this:

Offset colorbar notation

As an example of how it used to look (taken from one of my old papers, so different data etc.)

Proper colorbar notation

Using the most recent anaconda python 2.7, on MacOSX, mpl version 1.5.0

Edit: I should also note, tight_layout() does not improve this either, though it is missing from the working example.


Solution

  • You can simply use set_offset_position for the y-axis of the colorbar. Compare:

    fig, ax = plt.subplots()                
    im = ax.imshow(np.random.random((10,10)))                    
    cb = fig.colorbar(im)     
    cb.formatter.set_powerlimits((0, 0))
    cb.ax.yaxis.set_offset_position('right')                         
    cb.update_ticks()
    plt.show()
    

    enter image description here

    versus

    fig, ax = plt.subplots()
    im = ax.imshow(np.random.random((10,10)))
    cb = fig.colorbar(im)
    cb.formatter.set_powerlimits((0, 0))
    cb.ax.yaxis.set_offset_position('left')
    cb.update_ticks()
    plt.show()
    

    enter image description here

    All in all, it simply looks like the default has changed from right to left.