Python hide ticks but show tick labels

前端 未结 9 758
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:32

    This Worked out pretty well for me! try it out

    import matplotlib.pyplot as plt
    import numpy as np
    
    plt.figure()
    
    languages =['Python', 'SQL', 'Java', 'C++', 'JavaScript']
    pos = np.arange(len(languages))
    popularity = [56, 39, 34, 34, 29]
    
    plt.bar(pos, popularity, align='center')
    plt.xticks(pos, languages)
    plt.ylabel('% Popularity')
    plt.title('Top 5 Languages for Math & Data \nby % popularity on Stack Overflow', 
    alpha=0.8)
    
    # remove all the ticks (both axes), 
    plt.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off', 
    labelbottom='on')
    plt.show()
    
    0 讨论(0)
  • 2020-12-07 11:34

    Assuming that you want to remove some ticks on the Y axes and only show the yticks that correspond to the ticks that have values higher than 0 you can do the following:

    from import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    
    # yticks and yticks labels
    yTicks = list(range(26))
    yTicks = [yTick if yTick % 5 == 0 else 0 for yTick in yTicks]
    yTickLabels = [str(yTick) if yTick % 5 == 0 else '' for yTick in yTicks]
    

    Then you set up your axis object's Y axes as follow:

    ax.yaxis.grid(True)
    ax.set_yticks(yTicks)
    ax.set_yticklabels(yTickLabels, fontsize=6)
    fig.savefig('temp.png')
    plt.close()
    

    And you'll get a plot like this:

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

    Currently came across the same issue, solved as follows on version 3.3.3:

    My matplotlib ver: 3.3.3
    
    ax.tick_params(tick1On=False) for left and bottom ticks
    ax.tick_params(tick2On=False) for right and top ticks, which are off by default
    
    0 讨论(0)
  • 2020-12-07 11:50

    This worked for me:

    plt.tick_params(axis='both', labelsize=0, length = 0)
    
    0 讨论(0)
  • 2020-12-07 11:51

    You can set the tick length to 0 using tick_params (http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.tick_params):

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot([1],[1])
    ax.tick_params(axis=u'both', which=u'both',length=0)
    plt.show()
    
    0 讨论(0)
  • 2020-12-07 11:56

    While attending a coursera course on Python, this was a question.

    Below is the given solution, which I think is more readable and intuitive.

    ax.tick_params(top='off', bottom='off', left='off', right='off', labelleft='on', labelbottom='on')
    
    0 讨论(0)
提交回复
热议问题