【问题标题】:change formatting ticks of colorbar更改颜色条的格式刻度
【发布时间】:2020-08-03 21:44:49
【问题描述】:

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

我正在寻找的结果是在此处实现的等值线图 (Matplotlib Colorbar Ticks Mathtext Format)

这是一个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()

【问题讨论】:

  • @JohanC,是的,我试过了。结果和我已经有的一样。这就是为什么我说我正在寻找的结果与链接帖子中的结果相同。

标签: python matplotlib colorbar


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 2015-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多