Dave JPNY
Dave JPNY

Reputation: 123

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

Upvotes: 12

Views: 7206

Answers (1)

xnx
xnx

Reputation: 25508

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

Upvotes: 17

Related Questions