【问题标题】:Python matplotlib colorbar scientific notation basePython matplotlib colorbar 科学记数法库
【发布时间】:2017-09-05 13:19:43
【问题描述】:

我正在尝试在我的 matpllotlib 轮廓图上自定义颜色条。虽然我能够使用科学记数法,但我正在尝试更改记数法的基础 - 基本上是为了让我的刻度在 (-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()

像这样:

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

我该怎么做?

【问题讨论】:

    标签: python matplotlib colorbar contourf


    【解决方案1】:

    一种可能的解决方案是将ScalarFormatter 子类化并修复这个问题中的数量级:Set scientific notation with fixed exponent and significant digits for multiple subplots

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

    然后您可以通过颜色条的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_order_of_magnitude(self):
            self.orderOfMagnitude = self.oom
        def _set_format(self, vmin=None, vmax=None):
            self.format = self.fformat
            if self._useMathText:
                 self.format = r'$\mathdefault{%s}$' % 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()
    

    对于 matplotlib 版本

    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)
    

    【讨论】:

    • 人们还能重现这个吗?
    • @leb 是的,我可以很好地重现它!
    • 这真的很有用!我最终在__init__ 中设置了fformat="%g"
    【解决方案2】:

    与@ImportanceOfBeingErnes 所描述的类似,您可以使用FuncFormatter (docs),您只需将一个函数传递给它来确定刻度标签。这会为您的颜色条删除 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()
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-13
      • 1970-01-01
      • 1970-01-01
      • 2018-03-25
      • 2014-11-16
      • 2020-12-26
      相关资源
      最近更新 更多