简体   繁体   English

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

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

I have a contour plot in matplotlib using a colorbar which is created by我使用由创建的颜色条在 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)

带偏移的颜色条

How can I change the colorbar ticklabels (mantissa of exponent) showing up with only 2 digits after the '.'如何更改颜色条刻度标签(指数的尾数)在 '.' 后仅显示 2 位数字。 instead of 3 (keeping the off set notation)?而不是 3(保持偏移符号)? Is there a possibility or do I have to set the ticks manually?有没有可能还是我必须手动设置刻度? Thanks谢谢

I have tried to use the str formatter我曾尝试使用 str 格式化程序

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

so far but this doesn't give me the desired result.到目前为止,但这并没有给我想要的结果。

The problem is that while the FormatStrFormatter allows to set the format precisely, it is not capable of handling offsets like the 1e-7 in the case from the question.问题是,虽然FormatStrFormatter允许精确设置格式,但在问题的情况下,它无法处理像1e-7这样的偏移量。

On the other hand the default ScalarFormatter automatically selects its own format, without letting the user change it.另一方面,默认的ScalarFormatter自动选择自己的格式,而不让用户更改它。 While this is mostly desireable, in this case, we want to specify the format ourself.虽然这通常是可取的,但在这种情况下,我们希望自己指定格式。

A solution is to subclass the ScalarFormatter and reimplement its ._set_format() method, similar to this answer .一个解决方案是将ScalarFormatter子类ScalarFormatter并重新实现其._set_format()方法,类似于这个答案

Note that you would want "%.2f" instead of "%.2g" to always show 2 digits after the decimal point.请注意,您希望"%.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()

在此处输入图片说明

Sorry for getting in the loop so late.很抱歉这么晚才加入循环。 If you still are looking for a solution, an easier way is as follows.如果您仍在寻找解决方案,则更简单的方法如下。

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

Note: it's '%.2f' instead of '%.2g'.注意:它是 '%.2f' 而不是 '%.2g'。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM