phil
phil

Reputation: 3

Forcing x-axis of pyplot histogram (python, pandas)

Hi so I have a data called vc that looks like this.

It is a count of scores. The score range is from 0 to 40.

However, as shown below, there is only a few with actual counts. I can't make the histogram to have the x axis that I want..

d = {'count': [9, 30, 6, 2,3,1,1,4,1,1,2,2,6,3]}
vc = pd.DataFrame(data=d, index=[12,13,14,15,17,18,19,20,21,22,23,24,25,26])

vc
      index   count
        12       9
        13      30
        14       6
        15       2
        17       3
        18       1
        19       1
        20       4
    ...and so on

I want to make a histogram with x axis from 0 to 40, like this: histogram I want

However, my histogram doesn't show the scores with zero counts..

vc=vc.sort_index()
ax = vc.plot(kind='bar', legend=False)
ax.set_xlabel("score")
ax.set_ylabel("count")
ax.set_xticks(range(0,40,5))

The resulting histogram: enter image description here

How can I produce the wanted histogram in the first image? I've tried for hours but have sadly failed.. Thank you

Upvotes: 0

Views: 226

Answers (1)

StupidWolf
StupidWolf

Reputation: 46908

Maybe not a very clever solution, but you can plot a blank with the range you need, then plot over with your count table:

import pandas as pd
import matplotlib.pyplot as plt 

d = {'count': [9, 30, 6, 2,3,1,1,4,1,1,2,2,6,3]}
vc = pd.DataFrame(data=d, index=[12,13,14,15,17,18,19,20,21,22,23,24,25,26])
plt.bar(x=np.arange(10,40),height=0)
plt.bar(vc.index.to_list(),vc['count'])

enter image description here

Upvotes: 1

Related Questions