Leopoldo
Leopoldo

Reputation: 845

How to plot collections.Counter histogram using matplotlib?

How to plot histogram of following Counter object?:

w = collections.Counter()
l = ['a', 'b', 'b', 'b', 'c']
for o in l:
    w[o]+=1

Upvotes: 20

Views: 36507

Answers (2)

Sheldore
Sheldore

Reputation: 39072

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

Upvotes: 43

SV-97
SV-97

Reputation: 431

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()

Upvotes: 6

Related Questions