pythonpython-3.xmatplotlibscientific-notation

How does one show x10(superscript number) instead of 1e(number) for axes?


The only way I know how to use scientific notation for the end of the axes in matplotlib is with

plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0))

but this will use 1e instead of x10. In the example code below it shows 1e6, but I want x10 to the power of 6, x10superscript6 (x10^6 with the 6 small and no ^). Is there a way to do this?

edit: I do not want scientific notation for each tick in the axis (that does not look good imho), only at the end, like the example shows but with just the 1e6 part altered to x10superscript6.

I can't include images yet.

Thanks

import numpy as np
import matplotlib.pyplot as plt
plt.figure()
x = np.linspace(0,1000)
y = x**2
plt.plot(x,y)
plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
plt.show()

Solution

  • The offset is formatted differently depending on the useMathText argument. If True it will show the offset in a latex-like (MathText) format as x 10^6 instead of 1e6

    import numpy as np
    import matplotlib.pyplot as plt
    plt.figure()
    x = np.linspace(0,1000)
    y = x**2
    plt.plot(x,y)
    plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0), useMathText=True)
    plt.show()
    

    enter image description here

    Note that the above will not work for version 2.0.2 (possibly other older versions). In that case you need to set the formatter manually and specify the option:

    import numpy as np
    import matplotlib.pyplot as plt
    plt.figure()
    x = np.linspace(0,1000)
    y = x**2
    plt.plot(x,y)
    plt.gca().yaxis.set_major_formatter(plt.ScalarFormatter(useMathText=True))
    plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
    plt.show()