3
votes

I need to make a histogram in Python with grades distribution. I use matplotlib.

import matplotlib.pyplot as plt

plt.title('Histogram Grades')
data = [1, 3, 10, 8, 9, 5, 3, 7, 7, 3, 1, 3, 10, 8, 9, 5, 3, 7, 7, 3]
data.sort
plt.hist(data)
plt.ylabel('Count')
plt.show()

The histogram it's OK but I don't like the grouping python uses to show grades in x-axis. I wonder if there is a way (some hist parameter or another plot library), where I can have bars for each individual grade?

Thanks in advance.

2

2 Answers

1
votes

It can be a little fussy, but you can customize almost everything once you have the right arguments. The main problems seem to be getting bins right and setting the base width with rwidth.

Maybe this is closer to what you are hoping for:

import matplotlib.pyplot as plt

plt.title('Histogram Grades')
data = [1, 3, 10, 8, 9, 5, 3, 7, 7, 3, 1, 3, 10, 8, 9, 5, 3, 7, 7, 3, 2]
plt.hist(data, rwidth=.8, bins=np.arange(min(data), max(data)+2) - 0.5)

plt.xticks(np.arange(min(data), max(data)+1, 1.0))
plt.ylabel('Count')
plt.show()

enter image description here

0
votes

Since you want bar charts for the frequencies, I would personally recommend using Counter module to count the frequency. It returns a dictionary whose keys are the grades and the values are their corresponding frequencies. import matplotlib.pyplot as plt from collections import Counter

data = [1, 3, 10, 8, 9, 5, 3, 7, 7, 3, 1, 3, 10, 8, 9, 5, 3, 7, 7, 3]
freqs = Counter(data)
# Counter({1: 2, 3: 6, 10: 2, 8: 2, 9: 2, 5: 2, 7: 4})

plt.bar(freqs.keys(), freqs.values())
plt.ylabel('Count')
plt.title('Histogram Grades')
plt.show()

enter image description here