Search code examples
pythonmatplotlibgraphlogarithm

How to evenly space the grid on a matplotlib log scale


How can I set the scale of a log-scaled axis in matplotlib to show values less than base^1 and space them evenly?

Example:

I have a scale that looks like this:

enter image description here

But I want a scale that looks like this:

enter image description here


Solution

  • Your yaxis doesn't make sense, as a log scale has 0 at minus infinity. You can set a tick position at 0.01 via ax.set_ylim(ymin=0.01). This would have the same distance to 0.1 as the distance between 0.1 and 1.

    import matplotlib.pyplot as plt
    import numpy as np
    
    fig, ax = plt.subplots()
    ax.set_yscale('log')
    x = np.linspace(0.05, 100, 1000)
    ax.plot(x, x, 'r--')
    ax.yaxis.set_major_formatter(lambda x, pos: f'{x:g}')
    ax.set_ylim(ymin=0.01)
    plt.show()
    

    example of log scale y