-
- 1 #
- 2 # 本文以某一批产品的长度为数据集
- 3 # 在此数据集的基础上绘制直方图和正态分布曲线
- 4 #
- 5
- 6 import pandas as pd # pandas是一个强大的分析结构化数据的工具集
- 7 import numpy as np # numpy是Python中科学计算的核心库
- 8 import matplotlib.pyplot as plt # matplotlib数据可视化神器
- 9
- 10 # 正态分布的概率密度函数
- 11 # x 数据集中的某一具体测量值
- 12 # mu 数据集的平均值,反映测量值分布的集中趋势
- 13 # sigma 数据集的标准差,反映测量值分布的分散程度
- 14 def normfun(x, mu, sigma):
- 15 pdf = np.exp(-((x - mu) ** 2) / (2 * sigma ** 2)) / (sigma * np.sqrt(2 * np.pi))
- 16 return pdf
- 17
- 18 if __name__ == '__main__':
- 19
- 20 data = pd.read_csv('length.csv') # 载入数据文件
- 21 length = data['length'] # 获得长度数据集
- 22 mean = length.mean() # 获得数据集的平均值
- 23 std = length.std() # 获得数据集的标准差
- 24
- 25 # 设定X轴:前两个数字是X轴的起止范围,第三个数字表示步长
- 26 # 步长设定得越小,画出来的正态分布曲线越平滑
- 27 x = np.arange(2524, 2556, 0.1)
- 28 # 设定Y轴,载入刚才定义的正态分布函数
- 29 y = normfun(x, mean, std)
- 30 # 绘制数据集的正态分布曲线
- 31 plt.plot(x, y)
- 32
- 33 # 绘制数据集的直方图
- 34 plt.hist(length, bins=12, rwidth=0.9, density=True)
- 35 plt.title('Length distribution')
- 36 plt.xlabel('Length')
- 37 plt.ylabel('Probability')
- 38
- 39 # 输出正态分布曲线和直方图
- 40 plt.show()