Python matplotlib colorbar科学表示法基础

时间:2022-07-18 14:59:38

I am trying to customise a colorbar on my matpllotlib contourf plots. Whilst I am able to use scientific notation I am trying to change the base of the notation - essentially so that my ticks would be in the range of (-100,100) rather than (-10,10).

我想在我的matpllotlib轮廓图上定制一个颜色条。虽然我可以使用科学的符号,我试图改变符号的基础——本质上是这样,我的节拍将在(-100,100)范围内,而不是(-10,10)。

For example, this produces a simple plot...

例如,这产生了一个简单的情节……

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

like so:

像这样:

Python matplotlib colorbar科学表示法基础

However, I would like the label above the colorbar to be 1e-2 and the numbers to range from -10 to 10.

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

How would I go about this?

我该怎么做呢?

2 个解决方案

#1


2  

A possible solution can be to subclass the ScalarFormatter and fix the order of magnitude as in this question: Set scientific notation with fixed exponent and significant digits for multiple subplots

一种可能的解决方案是对ScalarFormatter进行子类化,并按照这个问题确定大小的顺序:为多个子图设置具有固定指数和有效数字的科学符号

You would then call this formatter with the order of magnitude as the argument order, OOMFormatter(-2, mathText=False). mathText is set to false to obtain the notation from the question, i.e. Python matplotlib colorbar科学表示法基础 while setting it to True, would give Python matplotlib colorbar科学表示法基础.

然后,您可以将这个格式化程序的大小顺序称为参数顺序OOMFormatter(-2, mathText=False)。mathText被设置为false以从问题中获得表示法,即当将其设置为True时,将给出。

You can then set the formatter to the colorbar via the colorbar's format argument.

然后可以通过colorbar的format参数将格式化程序设置为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()

Python matplotlib colorbar科学表示法基础

#2


1  

Similar to what @ImportanceOfBeingErnes described, you could use a FuncFormatter (docs) to which you just pass a function to determine the tick labels. This removes the auto generation of the 1e-2 header for your colorbar, but I imagine you can manually add that back in (I had trouble doing it, though was able to add it on the side). Using a FuncFormatter, you can just generate string tick values which has the advantage of not having to accept the way python thinks a number should be displayed.

类似于@ImportanceOfBeingErnes所描述的,您可以使用一个function formatter (docs),您只需向它传递一个函数来确定标记。这将删除colorbar的1e-2头文件的自动生成,但我认为您可以手动添加回该头文件(我在这方面遇到了麻烦,不过可以在旁边添加它)。使用FuncFormatter,您可以生成字符串tick值,该值的优点是不必接受python认为应该显示数字的方式。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as tk

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

levels = list(np.linspace(-.1,.1,9))

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

def my_func(x, pos):
    label = levels[pos]
    return str(label*100)

fmt1 = tk.FuncFormatter(my_func)

cbar = fig.colorbar(plot, format=fmt1)
cbar.set_label("1e-2")

plt.show()

This will generate a plot which looks like this.

这将产生一个像这样的图。

Python matplotlib colorbar科学表示法基础

#1


2  

A possible solution can be to subclass the ScalarFormatter and fix the order of magnitude as in this question: Set scientific notation with fixed exponent and significant digits for multiple subplots

一种可能的解决方案是对ScalarFormatter进行子类化,并按照这个问题确定大小的顺序:为多个子图设置具有固定指数和有效数字的科学符号

You would then call this formatter with the order of magnitude as the argument order, OOMFormatter(-2, mathText=False). mathText is set to false to obtain the notation from the question, i.e. Python matplotlib colorbar科学表示法基础 while setting it to True, would give Python matplotlib colorbar科学表示法基础.

然后,您可以将这个格式化程序的大小顺序称为参数顺序OOMFormatter(-2, mathText=False)。mathText被设置为false以从问题中获得表示法,即当将其设置为True时,将给出。

You can then set the formatter to the colorbar via the colorbar's format argument.

然后可以通过colorbar的format参数将格式化程序设置为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()

Python matplotlib colorbar科学表示法基础

#2


1  

Similar to what @ImportanceOfBeingErnes described, you could use a FuncFormatter (docs) to which you just pass a function to determine the tick labels. This removes the auto generation of the 1e-2 header for your colorbar, but I imagine you can manually add that back in (I had trouble doing it, though was able to add it on the side). Using a FuncFormatter, you can just generate string tick values which has the advantage of not having to accept the way python thinks a number should be displayed.

类似于@ImportanceOfBeingErnes所描述的,您可以使用一个function formatter (docs),您只需向它传递一个函数来确定标记。这将删除colorbar的1e-2头文件的自动生成,但我认为您可以手动添加回该头文件(我在这方面遇到了麻烦,不过可以在旁边添加它)。使用FuncFormatter,您可以生成字符串tick值,该值的优点是不必接受python认为应该显示数字的方式。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as tk

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

levels = list(np.linspace(-.1,.1,9))

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

def my_func(x, pos):
    label = levels[pos]
    return str(label*100)

fmt1 = tk.FuncFormatter(my_func)

cbar = fig.colorbar(plot, format=fmt1)
cbar.set_label("1e-2")

plt.show()

This will generate a plot which looks like this.

这将产生一个像这样的图。

Python matplotlib colorbar科学表示法基础