2013-03-27 156 views
1

所以说我有以下几点:用python对直方图中的值进行排序并绘制它们

[1,5,1,1,6,3,3,4,5,5,5,2, 5]

计数: 1-3 2-1 3-2 4-1 5-5 6-1

现在,我想打印这样排序的直方图的阴谋在x轴上,如:

不是:1 2 3 4 5 6

但通过将总数量排序:2 4 6 3 1 5

请帮我!谢谢...

我当前的绘图代码是:

plt.clf() 
    plt.cla() 
    plt.xlim(0,1) 
    plt.axvline(x=.85, color='r',linewidth=0.1) 
    plt.hist(correlation,2000,(0.0,1.0)) 
    plt.xlabel(index[thecolumn]+' histogram') 
    plt.ylabel('X Data') 

    savefig(histogramsave,format='pdf') 
+1

你是怎么试图做到这一点,哪里出了问题?发布你现在的代码,人们将能够提供帮助 - 就这样,我们将不得不编写整个事情。 – 2013-03-27 22:49:55

+0

plt.clf() \t \t plt.cla() \t \t plt.xlim(0,1) \t \t plt.axvline(X = 0.85,颜色= 'R',线宽= 0.1) \t \t plt.hist(相关,2000,(0.0,1.0)) \t \t plt.xlabel(指数[thecolumn] + '直方图 ') \t \t plt.ylabel(' 值') \t \t \t \t savefig(histogramsave ,format ='pdf') – 2013-03-27 22:52:57

+0

最好编辑那个int o你的问题,因此它是可读的。 – 2013-03-27 22:53:47

回答

3

使用collections.Counter,项目与sorted排序,通过在自定义按键功能:

>>> from collections import Counter 
>>> values = [1,5,1,1,6,3,3,4,5,5,5,2,5] 
>>> counts = Counter(values) 
>>> for k, v in sorted(counts.iteritems(), key=lambda x:x[::-1]): 
>>>  print k, v * 'x' 

2 x 
4 x 
6 x 
3 xx 
1 xxx 
5 xxxxx 
+0

嘿,事情是,我需要以与打印相同的方式绘制直方图。任何线索我怎么能做到这一点? – 2013-03-27 23:39:14

+0

@gran_profaci在上面的代码中,您可以将键和值(k,v)作为numpy数组,并使用matplotlib.pyplot.scatter(k,v) – viper 2013-04-08 00:31:11

0

史蒂芬看法是正确的。集合库可以完成你的提升。

如果您否则想要做手工的工作,你可以建立这样的事情:

data = [1,5,1,1,6,3,3,4,5,5,5,2,5] 
counts = {} 
for x in data: 
    if x not in counts.keys(): 
     counts[x]=0 
    counts[x]+=1 

tupleList = [] 
for k,v in counts.items(): 
    tupleList.append((k,v)) 

for x in sorted(tupleList, key=lambda tup: tup[1]): 
    print "%s" % x[0], 
print 
0

您必须计数和排序,如下面的例子中:

>>> from collections import defaultdict 
>>> l = [1,5,1,1,6,3,3,4,5,5,5,2,5] 
>>> d = defaultdict(int) 
>>> for e in l: 
...  d[e] += 1 
... 
>>> print sorted(d,key=lambda e:d[e]) 
[2, 4, 6, 3, 1, 5] 
相关问题