Search code examples
pythonmatplotlibcolorbar

change formatting ticks of colorbar


I'd like to change the colorbar ticks format of some plots I'm generating.

enter image description here

The result I'm looking for is the one achieved in here for a contour plot (Matplotlib Colorbar Ticks Mathtext Format)

This is a MWE to see my problem:

from matplotlib import pyplot as plt
from mpl_toolkits import axes_grid1
from matplotlib import colors, ticker
import numpy as np

def add_colorbar(im, aspect=15, pad_fraction=0.5, **kwargs):
    """Add a vertical color bar to an image plot."""
    divider = axes_grid1.make_axes_locatable(im.axes)
    width = axes_grid1.axes_size.AxesY(im.axes, aspect=1./aspect)
    pad = axes_grid1.axes_size.Fraction(pad_fraction, width)
    current_ax = plt.gca()
    cax = divider.append_axes("right", size=width, pad=pad)
    plt.sca(current_ax)
    cbar = im.axes.figure.colorbar(im, cax=cax, **kwargs)
    cbar.ax.yaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True, useOffset=True))
    cbar.ax.ticklabel_format(style='sci', scilimits=(0, 0))
    return cbar

im = plt.imshow(np.random.uniform(8000, 12000, (10,10)), norm=colors.LogNorm(),cmap=plt.cm.viridis)
cbar = add_colorbar(im)

plt.show()

Solution

  • ticklabel_format(..., scilimits=(m, n) can be used to force a scientific format for powers of 10 outside the range between m and n. With (0,0) scientific format will always be used.

    If you are using a lognorm, the colorbar gets both major and minor ticks especially to show log formatting. You can change their format and their position to standard ticks first, as follows:

    from matplotlib import pyplot as plt
    from mpl_toolkits import axes_grid1
    from matplotlib import ticker
    from matplotlib import colors
    import numpy as np
    
    def add_colorbar(im, aspect=15, pad_fraction=0.5, **kwargs):
        """Add a vertical color bar to an image plot."""
        divider = axes_grid1.make_axes_locatable(im.axes)
        width = axes_grid1.axes_size.AxesY(im.axes, aspect=1./aspect)
        pad = axes_grid1.axes_size.Fraction(pad_fraction, width)
        current_ax = plt.gca()
        cax = divider.append_axes("right", size=width, pad=pad)
        plt.sca(current_ax)
        cbar = im.axes.figure.colorbar(im, cax=cax, **kwargs)
        cbar.ax.yaxis.set_major_locator(ticker.AutoLocator())
        cbar.ax.yaxis.set_minor_locator(ticker.AutoLocator())
        cbar.ax.yaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True, useOffset=True))
        cbar.ax.xaxis.set_major_formatter(ticker.ScalarFormatter())
        cbar.ax.ticklabel_format(style='sci', scilimits=(0, 0))
        return cbar
    
    im = plt.imshow(np.random.uniform(8000, 12000, (10,10)), norm=colors.LogNorm())
    cbar = add_colorbar(im)
    
    plt.show()
    

    example plot