2017-04-10 62 views
9

matpllotlib contourfプロットでカラーバーをカスタマイズしようとしています。私は科学的表記法を使用することができますが、私は表記法のベースを変更しようとしています。つまり、ダニが(-10,100)ではなく(-100,100)の範囲にあるようにします。Python matplotlib colorbar科学的表記ベース

たとえば、これは単純なプロット...そうのような

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

可能な解決策は、ScalarFormatterをサブクラス化し、この質問のように大きさの順序を修正することができます:Set scientific notation with fixed exponent and significant digits for multiple subplots

あなたは、引数orderOOMFormatter(-2, mathText=False)として大きさの順で、このフォーマッタを呼び出します。 は、質問からの記法を得るためにfalseに設定されています。つまり、 enter image description here をTrueに設定するとenter image description hereとなります。

これで、カラーバーのformat引数でフォーマッタをカラーバーに設定できます。 @ImportanceOfBeingErnesを説明するものと同様に

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

、あなたはあなただけの目盛りラベルを決定するために関数を渡すためにどの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

関連する問題