Display numbers with "X" instead of "e" scientific notation in matplotlib

Using matplotlib, I would like to write text on my graphs, which are displayed in the usual scientific notation, for example, as 1.92x10 -7 instead of the standard 1.92e-7. I found help on how to do this for numbers representing ticks on axes, but not for a text function. Here is an example of my code that I would like to modify:

import numpy as np import matplotlib.pyplot as plt x = np.linspace(0,0.5) y = x*(1.0-x) a=1.92e-7 plt.figure() plt.plot(x, y) plt.text(0.01, 0.23, r"$a = {0:0.2e}$".format(a), size=20) plt.show() 
+7
python matplotlib
source share
1 answer

A slightly hacky way to do this is to create your own tex string for a number from its Python string representation. Skip as_si , defined below, your number and decimal places, and it will call this tex line:

 import numpy as np import matplotlib.pyplot as plt x = np.linspace(0,0.5) y = x*(1.0-x) def as_si(x, ndp): s = '{x:0.{ndp:d}e}'.format(x=x, ndp=ndp) m, e = s.split('e') return r'{m:s}\times 10^{{{e:d}}}'.format(m=m, e=int(e)) a=1.92e-7 plt.figure() plt.plot(x, y) plt.text(0.01, 0.23, r"$a = {0:s}$".format(as_si(a,2)), size=20) plt.show() 

enter image description here

+8
source share

All Articles