Search code examples
pythonmatplotlibxticks

How to set the range of minor ticks?


I'm working on a bar plot. The picture I've plot as following: enter image description here

To add the arrows in top and bottom axis, I set the spines color as 'none' first.

Then I plot arrow by using axes.arrow() function.

Finally, I reset the ticks by using axes.set_ticks() function.

I want to keep the minor ticks of top axis. But as what you've seen, the minor ticks in the left top corner is out of the arrow's range. How can I delete the part out of range?


Solution

  • The minor ticks can be set via set_minor_locator using a FixedLocator.

    An example:

    from matplotlib import pyplot as plt
    from matplotlib.ticker import FixedLocator
    
    fig, ax = plt.subplots()
    ax.set_xscale('log')
    ax.set_xlim(10**6, 1)
    ax.set_xticks([10**n for n in range(-1, 5)])
    ax.xaxis.set_minor_locator(FixedLocator(
        [k * 10**n for n in range(-1, 5) for k in range(2, 10) if k * 10**n <= 30000]))
    ax.xaxis.tick_top()
    plt.show()
    

    resulting plot