Search code examples
pythonmatplotlibbar-chartx-axis

Bar plot only shows the last tick_label


I want to plot random numbers of Bars with matplotlib. I set each tick_label individually but shows only the last one. Which one is correct? using tick_label property or using the plot set_xticks function?

import matplotlib.pyplot as plt
import random as r
        
for i in range(10):
    plt.bar(i,i*2, r.randint(1,2) , tick_label=i)
plt.show()

enter image description here


Solution

  • Assuming you cannot determine the number of bars in advance (before going in the loop), your can loop over the numbers and set the ticks on the fly with the code below. If you have text labels, there is also another example at the bottom of the answer for dealing with strings.

    import matplotlib.pyplot as plt
    import random as r
    
    # initialize labels list
    ticklabels = list()
    
    for i in range(10):
    
        # add a bar to the plot
        plt.bar(i, r.randint(1, 2))
    
        # append tick to the list & set current axes with
        ticklabels.append(i)
        plt.xticks(range(len(ticklabels)), labels=ticklabels)
    
    plt.show()
    

    This produces the following picture

    bar ticks within loop

    Then, if you happened to also get a string label within the loop, you can use it with the "label" keyword argument of the plt.xticks function:

    import matplotlib.pyplot as plt
    import random as r
    
    from string import ascii_uppercase as letters
    
    ticklabels = list()
    
    for i in range(10):
    
        # add a bar to the plot
        plt.bar(i, r.randint(1, 2))
    
        # append current tick label
        ticklabels.append(letters[r.randint(1, 25)])
        
        # set xaxis ticklabel
        plt.xticks(range(len(ticklabels)), labels=ticklabels)
    

    This will produce the picture below (with random labels).

    bar ticks labels within loop