用python对直方图中的值进行排序并绘制它们

2024-05-23 18:12:13 发布

您现在位置: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')

Tags: 代码绘图排序plthistcolor计数clf
3条回答

您必须对其进行计数和排序,如下例所示:

>>> 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]

使用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, count in reversed(counts.most_common()):
>>>     print(k, count * 'x')

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

史蒂文的想法是对的。藏书库可以帮你搬东西。

如果您不想手工完成此项工作,您可以构建如下内容:

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

相关问题 更多 >