【问题标题】:Ask for a way to plot histogram for a 1D array within python寻求一种在 python 中为一维数组绘制直方图的方法
【发布时间】:2014-06-12 07:22:09
【问题描述】:

对于一个系列:系列

0 111.8040373

2 140.10805914

4 117.64930612

5 111.85077526

6 137.22535711

7 138.59732811

...

123 103.63270617

您能否建议我绘制系列的直方图(例如熊猫)?我还想使用[0, 150] 范围内的 bin 宽度(例如 5)。我找到了一个similar question,但尝试了它并不能让它工作。

【问题讨论】:

  • 我不知道你对两个变量的直方图是什么意思。您希望它是什么样子?
  • @cdhagmann 很抱歉表达的模糊。例如,我将计算有多少个数据位于区间 (0,5),(5,10),...,( 145,150),分别。
  • 但是我们是在看0, 2, 4, ... 123 还是111.8040373... 系列?还是您希望两者兼得?
  • 我们只考虑第二列,第一列包括标签。
  • @ycy 谢谢!是的,你是对的! hist 可能会起作用。按照你的建议,我试过hist(series,bins=30, range=[0,150]).figure它可以工作,但是,当我尝试series.hist( bins=30, range=[0,150] )时,这个数字没有出来。

标签: python pandas series


【解决方案1】:

这是我个人用来制作直方图的脚本。

import numpy as np
import pylab as P

def binner(LB, UB, step=1):
    N = int((UB-LB+1)/float(step) + 1)
    return [LB + step * (i - 1/float(2)) for i in xrange(N)]

def f_hist(x, bins=None, param=20, h_type='bar', barwidth=0.8,filename=None):
    P.figure()
    if bins is None:
        if hasattr(param, "__iter__"):
            if len(param) == 2:
                LB, UB = param
                step = 1
            elif len(param) == 3:    
                LB, UB, step = param
            else:
                raise Exception
            bins = binner(LB, UB, step)
            n, bins, patches = P.hist(x,bins,histtype=h_type,rwidth=barwidth)
        else:
            n, bins, patches = P.hist(x,param,histtype=h_type,rwidth=barwidth)
    else:
        n, bins, patches = P.hist(x, bins, histtype=h_type, rwidth=barwidth)    
    if filename is None:
        P.show()
    else:
        P.savefig(filename)
        print "Histogram saved as {}".format(filename)
        return filename

if __name__ == '__main__':
    mu, sigma = 200, 25
    LB, UB, step = 100, 300, 10
    x = mu + sigma*P.randn(10000)
    f_hist(x, param = (LB, UB, step))
    f_hist(x)

您可以看到具有正态分布的示例案例。

【讨论】:

  • 步骤不应该是5吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-14
  • 2022-12-18
  • 1970-01-01
  • 2021-10-13
  • 2016-05-04
  • 2017-08-13
相关资源
最近更新 更多