在 matplotlib 中抑制科学记数法 offsetText

时间:2021-07-05 15:44:17

标签: python matplotlib

我在 y 轴上有一个带有科学记数法的图。我想特别禁止偏移/sci 符号文本,即轴顶部的 1e6

enter image description here

这与简单地关闭科学记数法不同,后者会使轴刻度标签25000002000000 等;我想按原样保留刻度标签,但只需隐藏顶部的小 1e6(因为轴标签已经显示“百万/年”)。有没有简单或“正确”的方法来做到这一点?

(我能想到的明显的 hack 是简单地将所有绘制的数据除以 1e6,但这并不容易推广,我想知道是否有一种解决方案不那么 hack。)

1 个答案:

答案 0 :(得分:1)

为了避免文本在公共乘数为 1e7 或更高时出错,最好将值除以 100 万。一个方便的方法是使用刻度格式器:

import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 4))
ax1.plot([0, 1.5e6])
ax1.yaxis.set_major_formatter(lambda x, pos: f'{x / 1e6:.1f}')
ax1.set_ylabel('incidents (millions/year)')
ax2.plot([0, 1.5e7])
ax2.yaxis.set_major_formatter(lambda x, pos: f'{x / 1e6:.1f}')
ax2.set_ylabel('incidents (millions/year)')
plt.tight_layout()
plt.show()

custom tick formatter

请注意,在较旧的 matplotlib 版本中,您无法直接设置格式化程序函数,并且需要显式 FuncFormatter