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()
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.
This produces the following picture
Then, if you happened to also get a string label within the loop, you can use it with the
"label"
keyword argument of theplt.xticks
function:This will produce the picture below (with random labels).