Reputation: 20688
Inspired by this answer ( https://stackoverflow.com/a/43826400/1175080 ) I wrote a Matplotlib code that can plot bar chart with labels like this:
import matplotlib.pyplot as plt
counts = [10, 20, 30, 40, 50]
labels = ['a', 'b', 'c', 'd', 'e']
plt.bar(range(0, len(counts)), counts)
plt.xticks(range(0, len(counts)), labels)
plt.show()
Output:
I want to know why we have to go through the multiple steps of first defining the x axis as integers and then place tick labels at tick positions?
Why can't we simply do this?
import matplotlib.pyplot as plt
counts = [10, 20, 30, 40, 50]
labels = ['a', 'b', 'c', 'd', 'e']
plt.bar(labels, counts)
plt.show()
This code also produces the same output as above.
Does the second method has any disadvantage or problem due to which the second method is not the right way to set bar chart labels in general?
Upvotes: 1
Views: 70
Reputation: 339430
The answer you link to has been written in May 2017.
Matplotlib 2.1, which is the first version to support categoricals (strings as input to bar
), was released 8 Oct 2017.
The only reason for the use of the range
in that linked answer is hence that at the time it was written, there was no alternative available.
Upvotes: 1