Search code examples
pythonmatplotlibscientific-notation

Matplotlib disable exponent notation in semilogy plots


Let's say I have the following code

import matplotlib.pyplot as plt
plt.figure()
plt.semilogy([0,1],[20,90])
plt.show()

which creates the following figure:

enter image description here

I would like to disable the scientific notation on the y-axis (so I would like to have 20, 30, 40, 60, instead of 2x10^1, etc.)

I already had a look at this thread, and I tried adding

import matplotlib.ticker
plt.gca().get_yaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
plt.gca().get_yaxis().get_major_formatter().set_scientific(False)
plt.gca().get_yaxis().get_major_formatter().set_useOffset(False)

but it does not affect the resulting figure. I am using python 3.5.3, and matplotlib 2.1.0. What am I missing?


Solution

  • Since the ticks on the y axis are within less than a decade, they are minor ticks, not major ticks. Hence you need to set the minor formatter to a ScalarFormatter.

    plt.gca().yaxis.set_minor_formatter(matplotlib.ticker.ScalarFormatter())

    Complete example:

    import matplotlib.pyplot as plt
    import matplotlib.ticker
    
    plt.figure()
    plt.semilogy([0,1],[20,90])
    plt.gca().yaxis.set_minor_formatter(matplotlib.ticker.ScalarFormatter())
    plt.show()
    

    enter image description here