How to adjust 'tick frequency' for string x-axis?

前端 未结 3 1887
隐瞒了意图╮
隐瞒了意图╮ 2021-01-02 05:09

I have a list to draw. Is there a way to display parts of x-axis labels, for example x[0], x[10], ..., but keep the figure the same?

x = [\'alice         


        
3条回答
  •  情歌与酒
    2021-01-02 05:36

    If I understand correctly you mention reducing the number of ticks displayed. There are multiple ways to do this depending on your plot, for example:

    Code Example:

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
        14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
        25, 26, 27, 28, 29, 30, 31, 32]
    
    y = [1, 4, 9, 6, 2, 4, 5, 6, 7, 2, 1, 
         4, 6, 5, 2, 3, 1, 4, 9, 6, 2, 4, 
         5, 6, 7, 2, 1, 4, 6, 5, 2, 3]
    
    labels = ["Ant", "Bob", "Crab", "Donkey", "Elephant", "Fire", "Giant","Hello",
              "Igloo", "Jump", "Bull","Even", "More", "Words", "other", "Bazboo", 
              "Ant", "Bob", "Crab", "Donkey", "Hippo", "Fire", "Giant","Hello",
              "Igloo", "Hump", "Kellogg","Even", "More", "Words", "Piano", "Foobar"]
    
    plt.xticks(x, labels[::2], rotation='vertical')
    plt.locator_params(axis='x', nbins=len(x)/2)
    plt.plot(x, y, 'g-', color='red')
    plt.tight_layout(pad=4)
    plt.subplots_adjust(bottom=0.15)
    plt.show()
    

    Using plt.locator_params and the length of your list it could be divided in half for example:

    plt.xticks(x, labels[::2], rotation='vertical') # set divisor
    plt.locator_params(axis='x', nbins=len(x)/2)  # set divisor 
    

    This should display half the number of ticks (x / 2) while keeping your plot uniform. This will work on strings and integers since the length (len) of x is working from a list.

    plt.xticks(x, labels, rotation='vertical')
    plt.locator_params(axis='x', nbins=len(x))
    

    If you want tighter spacing use no divisor or adjust accordingly.

提交回复
热议问题