我在另一个问题上看到,我可以使用它Counter()
来计算一组字符串中出现的次数.所以如果['A','B','A','C','A','A']
我得到了Counter({'A':3,'B':1,'C':1})
.但是现在,我如何使用该信息来构建直方图?
Igo*_*ato 66
对于您的数据,最好使用条形图而不是直方图.看看这段代码:
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()
Run Code Online (Sandbox Code Playgroud)
结果:
Phi*_*oud 17
您可以使用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')
Run Code Online (Sandbox Code Playgroud)
导致: