Fitting a histogram with python

后端 未结 5 1288
梦毁少年i
梦毁少年i 2020-11-28 02:18

I have a histogram

H=hist(my_data,bins=my_bin,histtype=\'step\',color=\'r\')

I can see that the shape is almost gaussian but I would like t

5条回答
  •  我在风中等你
    2020-11-28 02:48

    Here is another solution using only matplotlib.pyplot and numpy packages. It works only for Gaussian fitting. It is based on maximum likelihood estimation and have already been mentioned in this topic. Here is the corresponding code :

    # Python version : 2.7.9
    from __future__ import division
    import numpy as np
    from matplotlib import pyplot as plt
    
    # For the explanation, I simulate the data :
    N=1000
    data = np.random.randn(N)
    # But in reality, you would read data from file, for example with :
    #data = np.loadtxt("data.txt")
    
    # Empirical average and variance are computed
    avg = np.mean(data)
    var = np.var(data)
    # From that, we know the shape of the fitted Gaussian.
    pdf_x = np.linspace(np.min(data),np.max(data),100)
    pdf_y = 1.0/np.sqrt(2*np.pi*var)*np.exp(-0.5*(pdf_x-avg)**2/var)
    
    # Then we plot :
    plt.figure()
    plt.hist(data,30,normed=True)
    plt.plot(pdf_x,pdf_y,'k--')
    plt.legend(("Fit","Data"),"best")
    plt.show()
    

    and here is the output.

提交回复
热议问题