Using matplotlib, I would like to write text on my plots that displays in normal scientific notation, for example, as 1.92x10-7 instead of the default 1.92e-7. I have found help on how to do this for numbers labeling ticks on the axes but not for the text function. Here is an example of my code that I would like to change:
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()
MatPlotLib with Python To prevent scientific notation, we must pass style='plain' in the ticklabel_format method.
Use xticks() method to show all the X-coordinates in the plot. Use yticks() method to show all the Y-coordinates in the plot. To display the figure, use show() method.
Using style='plain' in the ticklabel_format() method, we can restrict the value being changed into exponential form.
Summary: Use the string literal syntax f"{number:. nf}" to suppress the scientific notation of a number to its floating-point representation.
A slightly hacky way of doing this is to build your own tex string for the number from its Python string representation. Pass as_si
, defined below, your number and a number of decimal places and it will produce this tex string:
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With