使用百分比单位绘制数据

时间:2011-04-26 20:36:44

标签: python matplotlib

我使用谷歌搜索,但我没有找到答案。

我的问题:

我有数据数组,我想使用百分比单位进行绘图。例如:

数据:[1,3,1,3,3,2,4,5]

  • 1:0.25

  • 2:0.125

  • 3:0.375

  • 4:0.125

  • 5:0.125

PS:我不想使用R只有python,matplotlib,如果需要numpy

2 个答案:

答案 0 :(得分:2)

答案 1 :(得分:1)

编辑:抱歉误读了你的问题,我以为你的意思只是python。有人希望发布一个matplotlib或numpy解决方案。

这是通过对列表进行排序来实现此目的的一种方法:

>>> a = [1, 3, 1, 3, 3, 2, 4, 5]
>>> 
>>> def unit_percents(L1):
...     ret = {}
...     L = L1[:]
...     sorted(L)
...     if L:
...         cur_count = 1
...         for i in range(len(L)-1):
...             cur_count+=1
...             if L[i] != L[i+1]:
...                 ret[L[i]]=float(cur_count)/len(L)
...                 cur_count=1
...         ret[L[-1]]=float(cur_count)/len(L)
...     return ret
... 
>>> unit_percents(a)
{1: 0.25, 2: 0.25, 3: 0.375, 4: 0.25, 5: 0.125}

也:

>>> dict([(x,float(a.count(x))/len(a)) for x in set(a)])
{1: 0.25, 2: 0.125, 3: 0.375, 4: 0.125, 5: 0.125}
>>>