Search code examples
pythonmatplotlibfloating-pointlegend

How to convert float notation to power of 10 scientific notation in Python?


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?


Solution

  • 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.