我只想绘制列表中重复次数最多的5个项目:
import matplotlib.pyplot as plt
import numpy as np
from collections import Counter
result= [162, 152, 47, 116, 34, 199, 69, 34, 51, 109, 89, 244, 30, 51, 151, 21, 88, 75, 75, 25, 221, 30, 75, 180, 21, 75, 41, 21, 30, 21, 183, 41, 117, 78, 88,162]
print(Counter(result))
counts= Counter(result)
common = counts.most_common()
labels = [item[0] for item in common]
number = [item[1] for item in common]
nbars = len(common)
plt.bar(np.arange(nbars), number, tick_label=labels)
plt.show()
我的代码绘制了所有项目,但是我只想重复5个。
答案 0 :(得分:2)
most_common()
可以为最常见的n
取一个可选数字n
:
>>> from collections import Counter
>>> result= [162, 152, 47, 116, 34, 199, 69, 34, 51, 109, 89, 244, 30, 51, 151, 21, 88, 75, 75, 25, 221, 30, 75, 180, 21, 75, 41, 21, 30, 21, 183, 41, 117, 78, 88,162]
>>> common = Counter(result).most_common(5)
>>> print(common)
[(21, 4), (75, 4), (30, 3), (162, 2), (41, 2)]