【问题标题】:Sort the values in a histogram in python and plot them [closed]在python中对直方图中的值进行排序并绘制它们[关闭]
【发布时间】:2013-03-27 22:43:04
【问题描述】:

假设我有以下内容:

[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')

【问题讨论】:

  • 您是如何尝试做到这一点的,哪里出了问题?发布您当前的代码,人们将能够提供帮助 - 事实上,我们将不得不编写整个事情。
  • 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('Value') savefig(histogramsave,format='pdf')
  • 最好将其编辑到您的问题中,以便阅读。
  • 哦,对不起!抱歉!

标签: python sorting matplotlib histogram


【解决方案1】:

使用collections.Counter,使用sorted对item进行排序,传入自定义key函数:

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

【讨论】:

  • 嘿,问题是,我需要以与打印相同的方式绘制直方图。任何线索我怎么能做到这一点?
  • @gran_profaci 在上面的代码中,您可以将键和值 (k, v) 作为 numpy 数组,并使用 matplotlib.pyplot.scatter(k, v) 进行散点图
【解决方案2】:

史蒂文的想法是正确的。馆藏图书馆可以帮您解决问题。

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

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

【讨论】:

    【解决方案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]
    

    【讨论】:

      猜你喜欢
      • 2020-12-19
      • 2018-10-26
      • 2019-07-20
      • 2018-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-27
      • 2019-09-28
      相关资源
      最近更新 更多