Observer
Observer

Reputation: 651

Plotting bar graph with the range in the x- axis -Python

Suppose I have a data such as the following, I want to plot a bar graph which would show each value of range as separate bar in the x-axis and the count in the yaxis.

                 range  count
0                  0-2  172
1                02-05   82
2                05-10  117
3                10-15  164
4                15-20  141
5         20 and above  380

I tried the following,

plt.bar(a['range'], a['count'], color='blue')

But i am getting the following error,

ValueError: invalid literal for float(): 0-2

I tried converting it to string. Still the result is same. Can anybody help me in plotting this here?

Thanks

Upvotes: 0

Views: 5677

Answers (1)

mprat
mprat

Reputation: 2481

If you look at the documentation for plt.bar, you need to specify as the first argument the left edges of the bars you want, not the labels. And to specify the xtick labels, you need to use the plt.xticks function. Something like this:

plt.bar(range(len(a['count'])), a['count'], color='blue')
plt.xticks(range(len(a['count'])), a['range'])

Upvotes: 2

Related Questions