在Python中使用Counter()建立直方图? [英] Using Counter() in Python to build histogram?

查看:463
本文介绍了在Python中使用Counter()建立直方图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在另一个问题上,我看到可以使用Counter()来计算一组字符串中出现的次数.因此,如果我有['A','B','A','C','A','A'],我会得到Counter({'A':3,'B':1,'C':1}).但是现在,我如何使用这些信息来构建直方图呢?

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?

推荐答案

对于您的数据,最好使用条形图而不是直方图.查看此代码:

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

结果:

这篇关于在Python中使用Counter()建立直方图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆