更改颜色条的格式刻度

change formatting ticks of colorbar

我想更改我正在生成的一些绘图的颜色栏刻度格式。

我正在寻找的结果是在此处获得的等高线图 ()

这是一个MWE看到我的问题:

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

ticklabel_format(..., scilimits=(m, n) 可用于强制使用 m 和 n 范围之外的 10 的幂的科学格式。 (0,0) 将始终使用科学格式。

如果您使用的是对数范数,颜色条会同时显示主要和次要刻度,尤其是为了显示日志格式。您可以先将它们的格式和位置更改为标准刻度,如下所示:

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