Python hide ticks but show tick labels

前端 未结 9 796
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条回答
  •  -上瘾入骨i
    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:

提交回复
热议问题