Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()
like image 533
Dave JPNY Avatar asked Jul 16 '15 11:07

Dave JPNY


People also ask

How do I avoid scientific notation in MatPlotLib?

MatPlotLib with Python To prevent scientific notation, we must pass style='plain' in the ticklabel_format method.

How do I show X values in MatPlotLib?

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.

How do you prevent numbers being changed to exponential form in Python MatPlotLib figure?

Using style='plain' in the ticklabel_format() method, we can restrict the value being changed into exponential form.

How do I get rid of E notation in Python?

Summary: Use the string literal syntax f"{number:. nf}" to suppress the scientific notation of a number to its floating-point representation.


1 Answers

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

enter image description here

like image 94
xnx Avatar answered Oct 19 '22 13:10

xnx