绘制正态分布曲线和直方图

时间:2019-06-21 21:08:38

标签: python numpy matplotlib scipy

请,我想知道如何绘制正态分布图。

这是我的代码:

import numpy as np
import scipy.stats as stats
import pylab as pl

h=[27.3,27.6,27.5,27.6,27.3,27.6,27.9,27.5,27.4,27.5,27.5,27.4,27.1,27.0,27.3,27.4]

fit = stats.norm.pdf(h, np.mean(h), np.std(h))  #this is a fitting indeed

pl.plot(h,fit,'-o')
pl.hist(h,density=True)      #use this to draw histogram of your data
pl.show()                    #use may also need add this

我尝试过,但是曲线很粗糙。

1 个答案:

答案 0 :(得分:0)

只需对列表h进行排序。

使用排序如下:

h = sorted([27.3,27.6,27.5,27.6,27.3,27.6,27.9,27.5,27.4,27.5,27.5,27.4,27.1,27.0,27.3,27.4])

或者,您也可以使用h.sort()

h =[27.3,27.6,27.5,27.6,27.3,27.6,27.9,27.5,27.4,27.5,27.5,27.4,27.1,27.0,27.3,27.4]
h.sort()

输出: enter image description here

为了获得平滑的分布曲线,可以使用seaborn.distplot()

import seaborn as sns
import scipy

h=[27.3,27.6,27.5,27.6,27.3,27.6,27.9,27.5,27.4,27.5,27.5,27.4,27.1,27.0,27.3,27.4]
ax = sns.distplot(h,fit=scipy.stats.norm, kde=False, hist=True, color='r')
ax.plot()

输出:

enter image description here

有关seaborn.distplot()的更多信息,请查看this官方文档。