Search code examples
pythonmatplotliblogarithmxticks

logarithmic axis major and minor ticks


In python's matplotlib, how can I make the logarithm x-axis ticks as the attached picture shows (i.e., major ticks with labels at every 0.5 spacing from 1 to 4.5; minor ticks without labels at every 0.1 spacing):

The appearance of final logarithm ticks

I've tried some methods such as

ax1.set_xticks([1.5,2,2.5,3,3.5,4,4.5])
ax1.xaxis.set_major_formatter(FormatStrFormatter('%.1f'))
ax1.xaxis.set_minor_locator(LogLocator(base=1,subs=(0.1,)))

But it doesn't give me the right solution.


Solution

  • You can set the location of the ticks using a MultipleLocator. You can set a different multiple for the major and minor ticks using ax.xaxis.set_major_locator and ax.xaxis.set_minor_locator.

    As for the formatting of the tick labels: you can set the major tick format using ax.xaxis.set_major_formatter with a ScalarFormatter and turn off the minor tick labels using ax.xaxis.set_minor_formatter with a NullFormatter.

    For example:

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    
    # set the xaxis to a logarithmic scale
    ax.set_xscale('log')
    
    # set the desired axis limits
    ax.set_xlim(1, 4.5)
    
    # set the spacing of the major ticks to 0.5
    ax.xaxis.set_major_locator(plt.MultipleLocator(0.5))
    
    # set the format of the major tick labels
    ax.xaxis.set_major_formatter(plt.ScalarFormatter())
    
    # set the spacing of the minor ticks to 0.1
    ax.xaxis.set_minor_locator(plt.MultipleLocator(0.1))
    
    # turn off the minor tick labels
    ax.xaxis.set_minor_formatter(plt.NullFormatter())
    
    plt.show()
    

    enter image description here