9

我想在轴上打印的值不是 30000 或 7000000,而是 30K 或 7M。这意味着为 x < 10^6 添加 K (kilo) 后缀,为 x >= 10^6 添加 M (mega) 后缀。我怎样才能做到这一点?

当前代码片段:

ax = pylab.gca()
formatter = matplotlib.ticker.FormatStrFormatter('%.f')
ax.xaxis.set_major_formatter(formatter)
4

2 回答 2

13

到目前为止,我得到的最好的代码是:

ax = matplotlib.pyplot.gca()
mkfunc = lambda x, pos: '%1.1fM' % (x * 1e-6) if x >= 1e6 else '%1.1fK' % (x * 1e-3) if x >= 1e3 else '%1.1f' % x
mkformatter = matplotlib.ticker.FuncFormatter(mkfunc)
ax.yaxis.set_major_formatter(mkformatter)
于 2011-08-12T12:23:56.663 回答
8

您将需要编写自己的函数来应用各种条件的后缀,并使用 FuncFormatter 而不是 StrFormatter。 这个例子应该涵盖你。

于 2011-07-02T16:07:59.820 回答