Cleanest way to hide every nth tick label in matplotlib colorbar?

前端 未结 4 1912
[愿得一人]
[愿得一人] 2020-11-27 04:08

The labels on my horizontal colorbar are too close together and I don\'t want to reduce text size further:

cbar = plt.colorbar(shrink=0.8, orientation=\'hori         


        
相关标签:
4条回答
  • 2020-11-27 04:17

    For loop the ticklabels, and call set_visible():

    for label in cbar.ax.xaxis.get_ticklabels()[::2]:
        label.set_visible(False)
    
    0 讨论(0)
  • 2020-11-27 04:18

    I use the following to show every 7th x label:

    plt.scatter(x, y)
    ax = plt.gca()
    temp = ax.xaxis.get_ticklabels()
    temp = list(set(temp) - set(temp[::7]))
    for label in temp:
        label.set_visible(False)
    plt.show()

    It's pretty flexible, as you can do whatever you want instead of plt.scatter. Hope it helps.

    0 讨论(0)
  • 2020-11-27 04:32

    One-liner for those who are into that!

    n = 7  # Keeps every 7th label
    [l.set_visible(False) for (i,l) in enumerate(ax.xaxis.get_ticklabels()) if i % n != 0]
    
    0 讨论(0)
  • 2020-11-27 04:34

    Just came across this thread, nice answers. I was looking for a way to hide every tick between the nth ticks. And found the enumerate function. So if anyone else is looking for something similar you can do it like this.

    for index, label in enumerate(ax.xaxis.get_ticklabels()):
        if index % n != 0:
            label.set_visible(False)
    
    0 讨论(0)
提交回复
热议问题