Python matplotlib colorbar科学记谱法基础

Joh*_*ohn 10 python matplotlib colorbar contourf

我正在尝试在matpllotlib contourf图上自定义颜色条.虽然我能够使用科学记数法,但我试图改变符号的基础 - 主要是因为我的刻度将在(-100,100)而不是(-10,10)的范围内.

例如,这会产生一个简单的情节......

import numpy as np
import matplotlib.pyplot as plt

z = (np.random.random((10,10)) - 0.5) * 0.2

fig, ax = plt.subplots()
plot = ax.contourf(z)
cbar = fig.colorbar(plot)

cbar.formatter.set_powerlimits((0, 0))
cbar.update_ticks()

plt.show()
Run Code Online (Sandbox Code Playgroud)

像这样:

在此输入图像描述

但是,我希望颜色条上方的标签为1e-2,数字范围为-10到10.

我该怎么做?

Imp*_*est 6

可能的解决方案是子集化ScalarFormatter并固定数量级,如下所示:为多个子图设置具有固定指数和有效数字的科学计数法

这样,你会调用该格式与大小作为参数的顺序orderOOMFormatter(-2, mathText=False)mathText设置为false以从问题中获取表示法,即 在此处输入图片说明 将其设置为True时, 在此处输入图片说明

然后,您可以通过colorbar的format参数将formatter设置为colorbar 。

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

class OOMFormatter(matplotlib.ticker.ScalarFormatter):
    def __init__(self, order=0, fformat="%1.1f", offset=True, mathText=True):
        self.oom = order
        self.fformat = fformat
        matplotlib.ticker.ScalarFormatter.__init__(self,useOffset=offset,useMathText=mathText)
    def _set_orderOfMagnitude(self, nothing):
        self.orderOfMagnitude = self.oom
    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.5) * 0.2

fig, ax = plt.subplots()
plot = ax.contourf(z)
cbar = fig.colorbar(plot, format=OOMFormatter(-2, mathText=False))

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明