【问题标题】:kilo (K) and mega (M) suffixes on matplotlib's axesmatplotlib 轴上的公斤 (K) 和兆 (M) 后缀
【发布时间】:2011-07-02 13:26:32
【问题描述】:
我想在轴上打印的值不是 30000 或 7000000,而是 30K 或 7M。这意味着为 x = 10^6 添加 M (mega) 后缀。我该怎么做?
当前代码sn-p:
ax = pylab.gca()
formatter = matplotlib.ticker.FormatStrFormatter('%.f')
ax.xaxis.set_major_formatter(formatter)
【问题讨论】:
标签:
python
formatter
matplotlib
ticker
【解决方案1】:
到目前为止,我得到的最好的代码是:
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)
【解决方案2】:
您需要编写自己的函数来应用各种条件的后缀,并使用 FuncFormatter 而不是 StrFormatter。 This example 应该覆盖你。