customizing just one side of tick marks in matplotlib using spines

11,607

Solution 1

you could simply use:

ax.tick_params(axis='y', direction='out')

this will orientate the ticks as you want. And:

ax.yaxis.tick_left()

this will not plot the right ticks

Solution 2

You can use:

ax.tick_params(top="off")
ax.tick_params(bottom="off")
ax.tick_params(right="off")
ax.tick_params(left="off")
Share:
11,607
Admin
Author by

Admin

Updated on June 21, 2022

Comments

  • Admin
    Admin almost 2 years

    I have a matplotlib horizontal bar drawn as follows:

    import matplotlib.pyplot as plt
    from numpy import *
    from scipy import *
    bars = arange(5) + 0.1
    vals = rand(5)
    print bars, vals
    plt.figure(figsize=(5,5), dpi=100)
    spines = ["bottom"]
    ax = plt.subplot(1, 1, 1)
    for loc, spine in ax.spines.iteritems():
      if loc not in spines:
        spine.set_color('none')
    # don't draw ytick marks
    #ax.yaxis.set_tick_params(size=0)
    ax.xaxis.set_ticks_position('bottom')
    plt.barh(bars, vals, align="center")
    plt.savefig("test.png") 
    

    This produces this image:enter image description here

    I wanted to only show the xaxis, which worked using spines, but now it plots these hanging tickmarks for the right-hand yaxis. How can I remove these? id like to keep the ytickmarks on the left hand side of the plot and make them face out (direction opposite to bars). I know that I can remove the ytickmarks altogether by uncommenting the line:

    #ax.yaxis.set_tick_params(size=0)
    

    but i want to keep the ytick marks only on the left hand side. thank you.

    EDIT: I achieved a solution after some trial and error though i'm sure my solution is probably not the best way to do it, so please let me know what you think still. i found that i can do:

    ax.spines["left"].axis.axes.tick_params(direction="outward") 
    

    to set the tick mark direction. to get rid of the right y-axis ticks, i use:

    ax.yaxis.set_ticks_position("left")