Bar plot only shows the last tick_label

1.1k views Asked by At

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

2

There are 2 answers

0
Leonard On BEST ANSWER

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

0
Quang Hoang On

As the comments already pointed out, every time you call plt.bar(tick_label=i) the tick label is overridden. To fix this, you can either move the tick format command outside of the for loop:

for i in range(10):
    plt.bar(i,i*2, r.randint(1,2))
    
plt.xticks(range(10))

Output:

enter image description here