Search code examples
matplotlibsubplotxticks

Minor and major tick marks both in and out on all subplot x-axes


I am having a subplot series where I want to display both minor and major tick marks on all x-axis in inner and outer directions for all of them. I tried something like :

fig, ax = plt.subplots(3,figsize=(10,6), sharex=True, gridspec_kw={'height_ratios': [3, 1,1]})
plt.subplots_adjust(hspace=.0)
ax[0].tick_params(top=True, labeltop=False, bottom=True, labelbottom=False, direction="in")

But some ticks on the top axix of the top plot are inwards some others are outward


Solution

  • Starting from a loop over the axis, using the tick_params() call you already have:

    for ax in axs:
        ax.tick_params(top=True, labeltop=False, bottom=True, labelbottom=False, direction="in")
    

    I want to display both minor and major tick marks

    Use the which parameter set to "both", which is by default "major".

    ax.tick_params(which="both", top=True, labeltop=False, bottom=True, labelbottom=False, direction="in")
    

    on all x-axis

    Use the axis parameter set to "x", which is by default "both".

    ax.tick_params(axis="x", which="both", top=True, labeltop=False, bottom=True, labelbottom=False, direction="in")
    

    in inner and outer directions for all of them

    Set the direction parameter to inout instead of in.

    ax.tick_params(axis="x", which="both", top=True, labeltop=False, bottom=True, labelbottom=False, direction="inout")
    

    Displaying the grid, here is the result

    fig, axs = plt.subplots(3,figsize=(10,6), sharex=True, gridspec_kw={'height_ratios': [3, 1,1]})
    plt.subplots_adjust(hspace=0)
    
    for ax in axs:
        ax.tick_params(axis="x", which="both", top=True, labeltop=False, bottom=True, labelbottom=False, direction="inout")
    

    enter image description here

    It's hard to see the ticks on the figure, you might want to play with the length parameter of the tick_params() function. Example:

    enter image description here

    Reference: Axes.tick_params doc