我找到了两个选项,第一个获取默认matplotlib.ticker.ScalarFormatter并关闭科学记数法:
fig, ax = plt.subplots()
ax.yaxis.get_major_formatter().set_scientific(False)
ax.yaxis.get_major_formatter().set_useOffset(False)
ax.plot([0, 1], [0, 2e7])
第二种方法定义了一个自定义格式化程序,它除以 1e6 并附加“百万”:
from matplotlib.ticker import NullFormatter
def formatter(x, pos):
return str(round(x / 1e6, 1)) + " million"
fig, ax = plt.subplots()
ax.yaxis.set_major_formatter(formatter)
ax.yaxis.set_minor_formatter(NullFormatter())
ax.plot([0, 1], [0, 2e7])
我在ScalarFormatter 中找不到将 1e6 替换为“百万”的方法,但我确信 matplotlib 中有一个方法可以让您在需要时做到这一点。
编辑:使用ax.text:
from matplotlib.ticker import NullFormatter
def formatter(x, pos):
return str(round(x / 1e6, 1))
fig, ax = plt.subplots()
ax.yaxis.set_major_formatter(formatter)
ax.yaxis.set_minor_formatter(NullFormatter())
ax.plot([0, 1], [0, 2e7])
ax.text(0, 1.05, "in millions", transform = ax.transAxes, ha = "left", va = "top")
当然,如果您已经有了一个标签,那么在其中包含它可能更有意义,我至少会这样做:
from matplotlib.ticker import NullFormatter
def formatter(x, pos):
return str(round(x / 1e6, 1))
fig, ax = plt.subplots()
ax.yaxis.set_major_formatter(formatter)
ax.yaxis.set_minor_formatter(NullFormatter())
ax.plot([0, 1], [0, 2e7])
ax.set_ylabel("interesting_unit in millions")
如果您确定您的数据已经以百万计并且在1e-4 和1e5 之间(在此范围之外scientific notation will kick in),您可以省略在最后两个方法中设置格式化程序的整个部分,只需添加ax.text(0, 1.05, "in millions", transform = ax.transAxes, ha = "left", va = "top") 或 ax.set_ylabel("interesting_unit in millions") 到您的代码。您仍然需要为其他两种方法设置格式化程序。