python-2.7 - 如何使用 matplotlib 颜色条中的偏移表示法更改尾数的位数

标签 python-2.7 matplotlib offset colorbar mantissa

我在 matplotlib 中有一个使用由创建的颜色条的等高线图

from mpl_toolkits.axes_grid1 import make_axes_locatable
divider = make_axes_locatable(axe) #adjust colorbar to fig height
cax = divider.append_axes("right", size=size, pad=pad)
cbar = f.colorbar(cf,cax=cax)
cbar.ax.yaxis.set_offset_position('left')
cbar.ax.tick_params(labelsize=17)#28
t = cbar.ax.yaxis.get_offset_text()
t.set_size(15)

Colorbar with offset

如何更改颜色条刻度标签(指数尾数)在“.”后仅显示 2 位数字而不是 3(保留偏移量符号)?是否有可能或者我必须手动设置刻度线?谢谢

我尝试过使用 str 格式化程序

cbar.ax.yaxis.set_major_formatter(FormatStrFormatter('%.2g'))

到目前为止,但这并没有给我想要的结果。

最佳答案

问题是,虽然 FormatStrFormatter 允许精确设置格式,但它无法像问题中的 1e-7 那样处理偏移量。

另一方面,默认的ScalarFormatter会自动选择自己的格式,而不让用户更改它。虽然这是最理想的,但在这种情况下,我们想自己指定格式。

解决方案是子类化ScalarFormatter并重新实现其._set_format()方法,类似于this answer .

请注意,您希望 "%.2f" 而不是 "%.2g" 始终显示小数点后 2 位数字。

import numpy as np; np.random.seed(0)
import matplotlib.pyplot as plt
import matplotlib.ticker

class FormatScalarFormatter(matplotlib.ticker.ScalarFormatter):
    def __init__(self, fformat="%1.1f", offset=True, mathText=True):
        self.fformat = fformat
        matplotlib.ticker.ScalarFormatter.__init__(self,useOffset=offset,
                                                        useMathText=mathText)
    def _set_format(self, vmin, vmax):
        self.format = self.fformat
        if self._useMathText:
            self.format = '$%s$' % matplotlib.ticker._mathdefault(self.format)

z = (np.random.random((10,10))*0.35+0.735)*1.e-7

fig, ax = plt.subplots()
plot = ax.contourf(z, levels=np.linspace(0.735e-7,1.145e-7,10))

fmt = FormatScalarFormatter("%.2f")

cbar = fig.colorbar(plot,format=fmt)

plt.show()

enter image description here

关于python-2.7 - 如何使用 matplotlib 颜色条中的偏移表示法更改尾数的位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53347465/

相关文章:

python-2.7 - Python 2.7 如何使用 str.split() 将字符串转换为函数外部的列表?

python-2.7 - pandas 数据帧到 oracle - NotImplementedError

python - 如何使用分类 sklearn 波士顿住房数据集通过 matplotlib 绘制线性图

ios - AdMob iOS 横幅偏移问题

组件(TASM): print the sum of certain bits in bytes

python - 为什么 super().__init__ 在子类化 threading.Thread 时不起作用?

regex - 正则表达式 : Ensuring b doesn't come between a and c

python - 如何为具有物理限制的随机点创建修改后的 voronoi 算法

python - 在绘制部分未定义的函数时遇到问题

sql - 确定记录在哪一页上