Making a histogram of string values in python

馋奶兔 提交于 2019-11-29 13:48:38
data =  ['32', '22', '12', '32', '22', '12', '31', '21', '11']
dict((x, data.count(x)) for x in data)

Result

{'11': 1, '12': 2, '21': 1, '22': 2, '31': 1, '32': 2}

Did you consider using collections.Counter?

# python 2.7
>>> l = ['32', '22', '12', '31', '21', '11', '32']
>>> import collections
>>> collections.Counter(l)
Counter({'32': 2, '11': 1, '12': 1, '21': 1, '22': 1, '31': 1})
data =  ['32', '22', '12', '32', '22', '12', '31', '21', '11']
sm = {i:0 for i in ['32', '22', '12', '31', '21','11']}
for i in data:
    sm[i] += 1
print sm

Something like this?

Assuming data is a list and you want to count the numbers in a bins. I will use bins as a dictionary.

bin = {'11': 0, '12': 0, '21': 0, '22': 0, '31': 0, '32': 0}

for element in data:
    if element in bin:  # Ignore other elements in data if any
        bin[element] = bin[element] + 1

bins dictionary will have frequency of each element in data list. Now you can use bins to plot bar graph using graph plot library. May be you can use this post to check matplotlib usage for plotting bar graph.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!