小能豆

使用 Matplotlib 绘制正态分布

python

请帮我绘制以下数据的正态分布:

数据:

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm

h = [186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
     187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
     161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180]

std = np.std(h) 
mean = np.mean(h)    
plt.plot(norm.pdf(h,mean,std))

输出:

Standard Deriviation = 8.54065575872 
mean = 176.076923077

情节不正确,我的代码有什么问题吗?


阅读 74

收藏
2024-05-18

共1个答案

小能豆

  • 注意:该解决方案使用的是pylab,而不是matplotlib.pyplot

您可以尝试将hist数据信息与拟合曲线一起放置,如下所示:

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

h = sorted([186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
     187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
     161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180])  #sorted

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

pl.plot(h,fit,'-o')

pl.hist(h,normed=True)      #use this to draw histogram of your data

pl.show()                   #use may also need add this 

在此输入图像描述

2024-05-18