matplotlib 如何使用偏移表示法更改尾数的彩条位数[重复]

zzwlnbp8  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(102)

此问题在此处已有答案

Scientific notation colorbar(4个答案)
三个月前就关门了。
我在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)

字符串


的数据
我如何改变颜色条ticklabels(指数的尾数)显示只有2位数字后的'.'而不是3(保持偏置符号)?是否有可能或我必须手动设置刻度?
我尝试使用str格式化程序

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


到目前为止,但这并没有给我给予想要的结果。

vaqhlq81

vaqhlq811#

  • 通过将matplotlib.ticker.FormatStrFormatter传递给format=参数,在创建过程中设置颜色条格式。
import matplotlib.ticker as tkr
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(2023)
z = (np.random.random((10,10))*0.35+0.735)*1.e-7

fig, ax = plt.subplots(figsize=(10, 7))

p1 = ax.contourf(z, levels=np.linspace(0.735e-7, 1.145e-7, 10))

# compare the formats of the two colorbars
cb1 = fig.colorbar(p1, format=tkr.FormatStrFormatter('%.9f'))
cb1.set_label('%.9f', labelpad=-40, y=1.05, rotation=0)

cb2 = fig.colorbar(p1, format=tkr.FormatStrFormatter('%.2g'))
cb2.set_label('%.2g', labelpad=-40, y=1.05, rotation=0)

字符串


的数据

  • 颜色条也可以在创建后进行格式化。
cb1 = fig.colorbar(p1)
cb1.ax.yaxis.set_major_formatter(tkr.FormatStrFormatter('%.9f'))
cb1.set_label('%.2g', labelpad=-40, y=1.05, rotation=0)

col17t5w

col17t5w2#

问题是,虽然FormatStrFormatter允许精确地设置格式,但它不能像问题中的1e-7那样处理偏移量。
另一方面,默认的ScalarFormatter会自动选择自己的格式,而不会让用户更改它。虽然这是最理想的,但在这种情况下,我们希望自己指定格式。
一个解决方案是子类化ScalarFormatter并重新实现它的._set_format()方法,类似于this answer
请注意,您希望"%.2f"而不是"%.2g"始终显示小数点后的两位数。

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

字符串


的数据

相关问题