所以说我有以下内容:
[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')
答案 0 :(得分:2)
使用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
答案 1 :(得分: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
答案 2 :(得分: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]