Below is the code for formatting an x value that I have been using.
Examples of what does it do:
- It formats 7,500,000 into 7.5 M
It formats 800,000 into 800 K It
def Formatting(self, x, pos): formats = ((1e-12,'%d%s T','%1.1f T'), (1e-9, '%d%s B','%1.1f B'), (1e-6, '%d%s M','%1.1f M'), (1e-3, '%d%s k','%1.1f K' )) for i, (N, A, B) in enumerate(formats): if abs(x) > (1./N): result = '' x = x * N if abs(x) >= 1000: x, r = divmod(x, 1000) result = ",%03d%s" % (r, result) return A % (x, result) else: return B % (x) elif 1 <= abs(x) < 1e3: return '%1.0f' % (x) elif 0.1 <= abs(x) < 1: return '%1.1f' % (x) elif 0 < abs(x) < 0.1: return '%1.3f' % (x) elif x == 0: return '%1.0f' % (x)
Now, I have been struggling to do the following improvements to it:
- Instead of 550 M, I would like to be able to print .55 B
- Instead of 550 B, I would like to be able to print .55 T
- Instead of 550 K, I would like to be able to print .55 M
- Instead of 0.001, I would like to be able to print .001 without the zero
- However 55.5 M, 55.5 B, 55.5 K should still be printed - not .055 M, or .055 B..
Suggestions as to how to perform this change or improve this piece of code to have more meaning printouts (that are used in a chart)?
Thank you very much!