8

In Python, I have values given by 0.000001,0.00001,0.0001,....,1.0 stored in my_Array (np.array). For each of these values I need to label a curve in a plot and store it in the legend as val = 10e-6 instead of val = 0.000001. The second version is automatically stored if I use (for the i'th value):

matplolib.pyplot.plot(...., label = 'val = ' + str(my_Array[i]))

Is there a function converting the float notation to the scientific power of 10 notation?

Giacomo
  • 551
  • 2
  • 4
  • 16

3 Answers3

12

You may use a combination of a ScalarFormatter and a FuncFormatter to format your values as mathtext. I.e. instead of 0.01 or 1e-2 it would look like enter image description here.

import matplotlib.pyplot as plt
import matplotlib.ticker as mticker

vals = [0.000001,0.00001,0.0001,0.01,1.0]

f = mticker.ScalarFormatter(useOffset=False, useMathText=True)
g = lambda x,pos : "${}$".format(f._formatSciNotation('%1.10e' % x))
fmt = mticker.FuncFormatter(g)

fig, ax = plt.subplots()
for i,val in enumerate(vals):
    ax.plot([0,1],[i,i], label="val = {}".format(fmt(val)))

ax.legend()    
plt.show()

enter image description here

This is essentially the same concept as in Can I show decimal places and scientific notation on the axis of a matplotlib plot?, just not for the axes, but the legend.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
1

You can just get the round between '%.2E%' and the desired number.

'%.2E' % Decimal('40800000000.00000000000000')

# returns '4.08E+10'

as seen on Display a decimal in scientific notation

The '%.2E%' rounds to the 2nd decimal point. To round to just the first one, use '%.1E%'.

-

To achieve what you want, just:

x = 0.0001
y = '%.2E' % x

print (y)

# prints 1.00E-04

(EDITED after jonrsharpe's tip)

Lodi
  • 565
  • 4
  • 16
1

In theory the below should work without the need to call private functions. However, something is broken in version 3.11 at least such that no check to the power limits is actually done inside ScalarFormatter.

import matplotlib.ticker as mticker
f = mticker.ScalarFormatter(useMathText=True)
f.set_powerlimits((-3,3))
"${}$".format(f.format_data(0.0001))
RCCG
  • 175
  • 2
  • 7