Python hide ticks but show tick labels

前端 未结 9 759
Happy的楠姐
Happy的楠姐 2020-12-07 11:23

I can remove the ticks with

ax.set_xticks([]) 
ax.set_yticks([]) 

but this removes the labels as well. Any way I can plot the tick labels b

相关标签:
9条回答
  • 2020-12-07 11:57

    matplotlib.pyplot.setp(*args, **kwargs) is used to set properties of an artist object. You can use this in addition to get_xticklabes() to make it invisible.

    something on the lines of the following

    import matplotlib.pyplot as plt
    fig = plt.figure()
    ax = fig.add_subplot(2,1,1)
    ax.set_xlabel("X-Label",fontsize=10,color='red')
    plt.setp(ax.get_xticklabels(),visible=False)
    

    Below is the reference page http://matplotlib.org/api/pyplot_api.html

    0 讨论(0)
  • 2020-12-07 11:58

    You can set the yaxis and xaxis set_ticks_position properties so they just show on the left and bottom sides, respectively.

    ax.yaxis.set_ticks_position('left')
    ax.xaxis.set_ticks_position('bottom')
    

    Furthermore, you can hide the spines as well by setting the set_visible property of the specific spine to False.

    axes[i].spines['right'].set_visible(False)
    axes[i].spines['top'].set_visible(False)
    
    0 讨论(0)
  • 2020-12-07 11:59

    Thanks for your answers @julien-spronck and @cmidi.
    As a note, I had to use both methods to make it work:

    import numpy as np
    import matplotlib.pyplot as plt
    
    fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(11, 3))
    
    data = np.random.random((4, 4))
    
    ax1.imshow(data)
    ax1.set(title='Bad', ylabel='$A_y$')
    # plt.setp(ax1.get_xticklabels(), visible=False)
    # plt.setp(ax1.get_yticklabels(), visible=False)
    ax1.tick_params(axis='both', which='both', length=0)
    
    ax2.imshow(data)
    ax2.set(title='Somewhat OK', ylabel='$B_y$')
    plt.setp(ax2.get_xticklabels(), visible=False)
    plt.setp(ax2.get_yticklabels(), visible=False)
    # ax2.tick_params(axis='both', which='both', length=0)
    
    ax3.imshow(data)
    ax3.set(title='Nice', ylabel='$C_y$')
    plt.setp(ax3.get_xticklabels(), visible=False)
    plt.setp(ax3.get_yticklabels(), visible=False)
    ax3.tick_params(axis='both', which='both', length=0)
    
    plt.show()
    

    0 讨论(0)
提交回复
热议问题