繁体   English   中英

创建不同集合的直方图

[英]Creating histogram of different sets

我正在分析某种产品的评级,我想创建一个直方图,其中包括每个评级在5星中的出现频率。 例如,我知道有2000个人说该产品是5星,有400个人说该产品是4星,依此类推,我想在直方图中显示它。

我有五个名为“五个”,“四个”,“三个”等的int值。

如何将它们放入直方图中,以显示5个评分评论与其他评分评论相比的数量? 您可能已经猜到了,Python是超级新手。

编辑:我从.tsv文件中获取了此数据,该文件有五列。 “评级”是五列之一。 我知道numpy和matplotlib,我只需要一点帮助就可以对直方图上的多个整数进行编码。

编辑:这是我的完整代码

import numpy as np
from numpy import arange,array,ones
from scipy import stats
import matplotlib.pyplot as plt
data = np.genfromtxt("amazon_alexa 2.tsv", delimiter = '\t', 
       skip_header = 1, dtype=str, encoding = 'UTF-8')


rating = data[0:,0] #first column
date = data[:,1] #second column
alexa_type = data[:,2] #third column
comment = data[:,3] #fourth column

rating_ = []
for r in rating:
    r = int(r)
    rating_.append(r)

five = 0
four = 0
three = 0
two = 0
one = 0


for r in rating_:
    if (r == 5):
        five = five + 1
    if (r == 4):
        four = four + 1
    if (r == 3):
        three = three + 1
    if (r == 2):
        two = two + 1
    if (r == 1):
        one = one + 1

它返回此:

Five Counter: 2286
Four Counter: 455
Three Counter: 152
Two Counter: 96
One Counter: 161

我想做成直方图

使用matplotlib库可让您直接从数据中绘图。 一个简单而肮脏的例子:

import random

from matplotlib import pyplot as plot

numbers = [random.randint(1, 5) for i in range(0, 100)]
plot.hist(numbers)
plot.show()

直方图的结果如下:

sample_histogram

可以通过更改plot变量来进行轴修改等操作。

您可以将其存储到字典中,然后:

ratings = {5: 2286, 4: 455, 3: 152, 2: 96, 1: 161}

tot = sum([ x for k, x in ratings.items()])
limit = 50
normalized = []
for x in ratings:
  normalized.append( ( x, int(limit*(ratings[x]/tot)) ) )

for k, v in normalized:
  print(str(k) + ': ' + '*'*v)

normalized外观如下所示,您可以直接从代码中构建它,而无需任何字典:

[(5, 36), (4, 7), (3, 2), (2, 1), (1, 2)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM