how to turn on minor ticks only on y axis matplotlib

前端 未结 5 1823
故里飘歌
故里飘歌 2020-12-07 17:08

How can I turn the minor ticks only on y axis on a linear vs linear plot?

When I use the function minor_ticks_on to turn minor ticks on, they appear on

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-07 18:06

    To clarify the procedure of @emad's answer, the steps to show minor ticks at default locations are:

    1. Turn on minor ticks for an axes object, so locations are initialized as Matplotlib sees fit.
    2. Turn off minor ticks that are not desired.

    A minimal example:

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    plt.plot([1,2])
    
    # Currently, there are no minor ticks,
    #   so trying to make them visible would have no effect
    ax.yaxis.get_ticklocs(minor=True)     # []
    
    # Initialize minor ticks
    ax.minorticks_on()
    
    # Now minor ticks exist and are turned on for both axes
    
    # Turn off x-axis minor ticks
    ax.xaxis.set_tick_params(which='minor', bottom=False)
    

    Alternative Method

    Alternatively, we can get minor ticks at default locations using AutoMinorLocator:

    import matplotlib.pyplot as plt
    import matplotlib.ticker as tck
    
    fig, ax = plt.subplots()
    plt.plot([1,2])
    
    ax.yaxis.set_minor_locator(tck.AutoMinorLocator())
    

    Result

    Either way, the resulting plot has minor ticks on the y-axis only.

提交回复
热议问题