如何用千(K)和兆(M)后缀格式化刻度标签

11 投票
2 回答
5816 浏览
提问于 2025-04-16 20:42

我想在坐标轴上显示数值时,不想看到像30000或7000000这样的数字,而是希望显示成30K或7M。这里的K代表千,M代表百万。也就是说,当数字小于100万时,加上K,当数字大于等于100万时,加上M。我该怎么做呢?

下面是当前的代码片段:

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

2 个回答

19

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

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)
9

你需要自己写一个函数,根据不同的情况来添加后缀,并使用 FuncFormatter 而不是 StrFormatter。这个例子应该能帮助你理解。

撰写回答