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

时间:2011-07-02 13:26:33

标签: python formatter matplotlib ticker

我想在轴上打印的值不是30000或7000000,而是30K或7M。这意味着为x<添加K(千)后缀。对于x> = 10 ^ 6,10 ^ 6和M(兆)后缀。我怎么能这样做?

当前代码段:

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

2 个答案:

答案 0 :(得分:7)

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

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)

答案 1 :(得分:4)

您需要编写自己的函数应用各种条件的后缀并使用FuncFormatter而不是StrFormatter。 This example应该涵盖你。