自定义matplotlib偏移量的偏移

时间:2018-12-13 17:09:11

标签: python python-3.x matplotlib

This question解决了我当前面临的问题。我有一些数据,例如[12.301, 12.318, 12.302],在绘制时会导致偏移显示为+1.23e1

我不介意偏移量本身,但是那种指数形式而不是仅仅写12.3并不是很好。我能以某种方式强迫指数仅以三的10的幂出现吗?用1e3代替1000是有道理的,根本不是用1e1代替10

我发现this other question有点相关,但这与仅具有整数形式有关,而我不介意小数。

1 个答案:

答案 0 :(得分:1)

在网络上进行了一些搜索并修改了找到的答案hereherehere加上ng s --host 0.0.0.0 --port 4200 & 之后,我就可以修改第一个链接的帖子:

print(dir(ScalarFormatter))

通常,该想法是计算数字的指数和尾数,然后对两者进行处理,以使指数为3的倍数(import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import ScalarFormatter, FormatStrFormatter #from https://stackoverflow.com/a/45332730/2454357 def fexp(f): return int(np.floor(np.log10(abs(f)))) if f != 0 else 0 #from https://stackoverflow.com/a/45332730/2454357 def fman(f): return f/10**fexp(f) #adapted from https://stackoverflow.com/a/3679918/2454357 class PowerMultipleOfThreeFormatter(ScalarFormatter): """Formats axis ticks using scientific notation with a constant order of magnitude""" def __init__(self, useOffset=True, useMathText=False): ScalarFormatter.__init__(self, useOffset=useOffset, useMathText=useMathText) def _set_orderOfMagnitude(self, range): """Over-riding this to avoid having orderOfMagnitude reset elsewhere""" exponent = fexp(range) if -3 < exponent < 3: self.orderOfMagnitude = 0 else: new_exp = (exponent//3)*3 self.orderOfMagnitude = new_exp def format_data(self, *args, **kwargs): ##make sure that format_data does everyting it shoud: super(PowerMultipleOfThreeFormatter, self).format_data( *args, **kwargs ) ##compute the offset in the right format exponent = fexp(self.offset) mantissa = fman(self.offset) if -3 < exponent < 3: return '{:g}'.format(self.offset) new_exp = (exponent//3)*3 factor = 10**new_exp ##from https://stackoverflow.com/a/2440786/2454357 man_string = '{}'.format(self.offset/factor).rstrip('0').rstrip('.') return man_string+'e{}'.format(new_exp) # Generate some random data... x = np.linspace(55478, 55486, 100) y = np.random.random(100) - 0.5 y = np.cumsum(y) y *= 1e-8 # Plot the data... fig,axes = plt.subplots(nrows=2, ncols=2) for ax, y0 in zip(axes.ravel(), [-1e4, 1.15e-4, 12, -0.1]): ax.plot(x, y+y0, 'b-') ax.yaxis.set_major_formatter(PowerMultipleOfThreeFormatter()) fig.tight_layout() plt.show() (exponent//3)*3)。对于乘数,已经证明了here,应该在何处以及如何添加这些计算(即在exponent%3中)。偏移值存储在_set_orderOfMagnitude中,字符串表示形式在函数ScalarFormatter.offset中进行计算。重载该功能后,我们可以更改偏移量的显示方式。该代码还包含一个示例,说明如何使用新的格式化程序(再次从here中无耻地复制了如何生成数据的方式)。代码的结果如下所示:

result of above code