20

How to plot histogram of following Counter object?:

w = collections.Counter()
l = ['a', 'b', 'b', 'b', 'c']
for o in l:
    w[o]+=1
Leopoldo
  • 795
  • 2
  • 8
  • 23
  • The constructor for `Counter` can take a list directly and give you the count, so your code can be replaced with `collections.Counter(['a', 'b', 'b', 'b', 'c'])`. And have you tried [matplotlib.pyplot.hist](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.hist.html)? – MatsLindh Sep 29 '18 at 20:06
  • 2
    Possible duplicate of [Using Counter() in Python to build histogram?](https://stackoverflow.com/questions/19198920/using-counter-in-python-to-build-histogram) – rahlf23 Sep 29 '18 at 20:07

2 Answers2

41

Looking at your data and attempt, I guess you want a bar plot instead of a histogram. Histogram is used to plot a distribution but that is not what you have. You can simply use the keys and values as the arguments of plt.bar. This way, the keys will be automatically taken as the x-axis tick-labels.

import collections
import matplotlib.pyplot as plt
l = ['a', 'b', 'b', 'b', 'c']
w = collections.Counter(l)
plt.bar(w.keys(), w.values())

enter image description here

Sheldore
  • 37,862
  • 7
  • 57
  • 71
6

I'm guessing this is what you want to do? You'd just have to add xtick labels(see matplotlib documentation)

import matplotlib.pyplot as plt
import collections

l = ['a', 'b', 'b', 'b', 'c']

count = collections.Counter(l)
print(count)

plt.bar(range(len(count)), count.values())
plt.show()
SV-97
  • 431
  • 3
  • 15