[英]change formatting ticks of colorbar
I'd like to change the colorbar ticks format of some plots I'm generating.我想更改我正在生成的一些图的颜色条刻度格式。
The result I'm looking for is the one achieved in here for a contour plot ( Matplotlib Colorbar Ticks Mathtext Format )我正在寻找的结果是在这里实现的轮廓 plot ( Matplotlib Colorbar Ticks Mathtext Format )
This is a MWE to see my problem:这是一个 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)
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. ticklabel_format(..., scilimits=(m, n)
可用于在 m 和 n 之间的范围之外强制 10 的幂的科学格式。始终使用(0,0)
科学格式。
If you are using a lognorm, the colorbar gets both major and minor ticks especially to show log formatting.如果您使用的是 lognorm,颜色条会同时获得主要和次要刻度,尤其是显示日志格式。 You can change their format and their position to standard ticks first, as follows:您可以先将它们的格式和它们的 position 更改为标准刻度,如下所示:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.