Python matplotlib colorbar科学记谱法基础

时间:2017-04-10 13:12:47

标签: 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()
像这样:

enter image description here

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

我该怎么做?

2 个答案:

答案 0 :(得分:4)

一个可能的解决方案可以是ScalarFormatter的子类,并按照此问题修正数量级:Set scientific notation with fixed exponent and significant digits for multiple subplots

然后,您将调用此格式化程序,其数量级为参数orderOOMFormatter(-2, mathText=False)mathText设置为false以从问题中获取符号,即 enter image description here 将其设置为True时,会给enter image description here

然后,您可以通过颜色条的format参数将格式化程序设置为颜色条。

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

enter image description here

答案 1 :(得分:1)

与@ImportanceOfBeingErnes描述的类似,您可以使用FuncFormatterdocs)来传递函数以确定刻度标签。这会删除为您的颜色条自动生成1e-2标题,但我想你可以手动添加它(我无法做到这一点,虽然能够在侧面添加它)。使用FuncFormatter,您只需生成字符串刻度值,其优点是不必接受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()

这将生成一个看起来像这样的图。

Contour Plot