Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kilo (K) and mega (M) suffixes on matplotlib's axes

I would like to print values on axes not as 30000 or 7000000 but as 30K or 7M. It means to add K (kilo) suffix for x < 10^6 and M (mega) suffix for x >= 10^6. How can I do that?

Current code snippet:

ax = pylab.gca()
formatter = matplotlib.ticker.FormatStrFormatter('%.f')
ax.xaxis.set_major_formatter(formatter)
like image 874
Nikolay Vyahhi Avatar asked Jul 02 '11 13:07

Nikolay Vyahhi


2 Answers

The best code to which I've come so far is:

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)
like image 183
Nikolay Vyahhi Avatar answered Oct 23 '22 03:10

Nikolay Vyahhi


You will need to write your own function applies the suffixes for various conditions and use FuncFormatter instead of StrFormatter. This example should cover you.

like image 20
Paul Avatar answered Oct 23 '22 04:10

Paul