I saw on another question that I could use Counter()
to count the number of occurrences in a set of strings. So if I have ['A','B','A','C','A','A']
I get Counter({'A':3,'B':1,'C':1})
. But now, how can I use that information to build a histogram for example?
49
66
For your data it is probably better to use a barchart instead of a histogram. Check out this code:
from collections import Counter
import numpy as np
import matplotlib.pyplot as plt
labels, values = zip(*Counter(['A','B','A','C','A','A']).items())
indexes = np.arange(len(labels))
width = 1
plt.bar(indexes, values, width)
plt.xticks(indexes + width * 0.5, labels)
plt.show()
Result:
-
1What if OP's data was best suited to a histogram? I know it's late to the game, but I'd like to update your answer to apply to a histogram example (but I'm not sure how to do it yet). That would answer the title to the question. – Thomas Matthew May 16 '16 at 15:49
-
@ThomasMatthew technically, it is a histogram. "barchart instead of histogram" is more referring to the use of
matplotlib.pyplot.bar
instead ofmatplotlib.pyplot.hist
. I believebar
goes better withCounter
(which is what OP wanted), that's it – Igonato May 16 '16 at 22:55 -
-
@ThomasMatthew how did you get there, what were you searching for? Does it score high on google? What query? If it shows on something other than
python Counter matplotlib
maybe it makes sense to edit the answer – Igonato May 16 '16 at 22:57 -
2I searched "build histogram from counter" and it was Google search result #1. It's also almost the same title of OP's question. It's worth an update for all the folks who search that query, which may be a high percentage views on this question. You might get more up votes and favorites you update (add) the histogram example – Thomas Matthew May 17 '16 at 3:11
17
You can write some really concise code to do this using pandas:
In [24]: import numpy as np
In [25]: from pandas import Series
In [27]: sample = np.random.choice(['a', 'b'], size=10)
In [28]: s = Series(sample)
In [29]: s
Out[29]:
0 a
1 b
2 b
3 b
4 a
5 b
6 b
7 b
8 b
9 a
dtype: object
In [30]: vc = s.value_counts()
In [31]: vc
Out[31]:
b 7
a 3
dtype: int64
In [32]: vc = vc.sort_index()
In [33]: vc
Out[33]:
a 3
b 7
dtype: int64
In [34]: vc.plot(kind='bar')
Resulting in:
help
ordir
function on an object in order to find out what methods and attributes are available for it. – sjakobi Oct 5 '13 at 15:57