2017-04-10 221 views
9

我想要在我的matpllotlib contourf圖上自定義一個顏色條。雖然我能夠使用科學記數法,但我試圖改變記譜法的基礎 - 實質上是爲了使我的蜱數在(-100,100)範圍內,而不是(-10,10)。Python matplotlib colorbar科學記數法base

例如,這將產生一個簡單的情節...

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

來描述了@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