matplotlib轴上的千(K)和兆(M)后缀

Nik*_*hhi 6 python matplotlib formatter ticker

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

当前代码段:

ax = pylab.gca()
formatter = matplotlib.ticker.FormatStrFormatter('%.f')
ax.xaxis.set_major_formatter(formatter)
Run Code Online (Sandbox Code Playgroud)

Nik*_*hhi 8

到目前为止,我遇到的最佳代码是:

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)
Run Code Online (Sandbox Code Playgroud)


Pau*_*aul 5

您将需要编写自己的函数以针对各种情况应用后缀,并使用FuncFormatter代替StrFormatter。 这个例子应该涵盖了您。