簡體   English   中英

如何使用matplotlib colorbar中的偏移表示法更改尾數的位數

[英]How to change the the number of digits of the mantissa using offset notation in matplotlib colorbar

我使用由創建的顏色條在 matplotlib 中有一個等高線圖

from mpl_toolkits.axes_grid1 import make_axes_locatable
divider = make_axes_locatable(axe) #adjust colorbar to fig height
cax = divider.append_axes("right", size=size, pad=pad)
cbar = f.colorbar(cf,cax=cax)
cbar.ax.yaxis.set_offset_position('left')
cbar.ax.tick_params(labelsize=17)#28
t = cbar.ax.yaxis.get_offset_text()
t.set_size(15)

帶偏移的顏色條

如何更改顏色條刻度標簽(指數的尾數)在 '.' 后僅顯示 2 位數字。 而不是 3(保持偏移符號)? 有沒有可能還是我必須手動設置刻度? 謝謝

我曾嘗試使用 str 格式化程序

cbar.ax.yaxis.set_major_formatter(FormatStrFormatter('%.2g'))

到目前為止,但這並沒有給我想要的結果。

問題是,雖然FormatStrFormatter允許精確設置格式,但在問題的情況下,它無法處理像1e-7這樣的偏移量。

另一方面,默認的ScalarFormatter自動選擇自己的格式,而不讓用戶更改它。 雖然這通常是可取的,但在這種情況下,我們希望自己指定格式。

一個解決方案是將ScalarFormatter子類ScalarFormatter並重新實現其._set_format()方法,類似於這個答案

請注意,您希望"%.2f"而不是"%.2g"始終在小數點后顯示 2 位數字。

import numpy as np; np.random.seed(0)
import matplotlib.pyplot as plt
import matplotlib.ticker

class FormatScalarFormatter(matplotlib.ticker.ScalarFormatter):
    def __init__(self, fformat="%1.1f", offset=True, mathText=True):
        self.fformat = fformat
        matplotlib.ticker.ScalarFormatter.__init__(self,useOffset=offset,
                                                        useMathText=mathText)
    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.35+0.735)*1.e-7

fig, ax = plt.subplots()
plot = ax.contourf(z, levels=np.linspace(0.735e-7,1.145e-7,10))

fmt = FormatScalarFormatter("%.2f")

cbar = fig.colorbar(plot,format=fmt)

plt.show()

在此處輸入圖片說明

很抱歉這么晚才加入循環。 如果您仍在尋找解決方案,則更簡單的方法如下。

    import matplotlib.ticker as tick
    cbar.ax.yaxis.set_major_formatter(tick.FormatStrFormatter('%.2f'))

注意:它是 '%.2f' 而不是 '%.2g'。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM