2

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

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Mironline
  • 2,755
  • 7
  • 35
  • 61
  • What do you expect to achieve with the second parameter `i*2`? `plt.bar` uses it for the height, while `r.randint(1,2)` is used for the width (creating overlap when the value is larger than 1). Removing the for-loop is a possibility `plt.bar(range(10), [r.randint(1, 2) for i in range(10)], tick_label=range(10))`. – JohanC Oct 04 '20 at 15:38
  • @JohanC I just made this loop to show that bars are generated in iterations. your code works perfectly, but how can run that in a loop instead of the in-line loop? – Mironline Oct 04 '20 at 15:47
  • In that case you need to put `tick_label=i` outside the loop. E.g. `plt.ticks(range(10))`. You still need to think about the other parameters to `plt.bar` though. Maybe `for i in range(10): plt.bar(i, r.randint(1,2))` ? – JohanC Oct 04 '20 at 15:55

2 Answers2

1

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

Leonard
  • 2,510
  • 18
  • 37
0

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

Quang Hoang
  • 146,074
  • 10
  • 56
  • 74