Python数据分析基础与应用电子活页7-20使用numpy库的histogram()函数和pyplot子模块的hist()函数绘制直方图.docx
Python数据分析基础与应用
模块
PAGE2
PAGE21
电子活页7-20使用NumPy库的histogram()函数和Pyplot子模块的hist()函数绘制直方图
【技能训练7-12】
使用numpy库的histogram()函数和pyplot子模块的hist()函数绘制直方圆。
【训练要求】
在JupyterNotebook开发环境中创建Jt-12.ipymb,然后编写代码使用numpy库的histogram()函数和pyplot子模块的hist()函数绘制直方圆。
【实施过程】
(1)输出histogram()函数的返回值hist与bin_edges
代码如下:
importnumpyasnp
array1=np.arange(8)
hist,bin_edges=np.histogram(array1,density=True)
print(hist)
print(bin_edges)
输出结果:
[0000.000.000
[0.0.71.42.12.83.54.24.95.66.37.]
(2)创建数字直方图
代码如下:
importnumpyasnp
array2=np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27])
#返回hist
np.histogram(array2,bins=[0,20,40,60,80,100])
#返回bins
hist,bins=np.histogram(array2,bins=[0,20,40,60,80,100])
print(hist)
print(bins)
输出结果:
[34521]
[020406080100]
(3)使用Pyplot子模块的hist()函数创建直方图
上面的直方图的数字表示形式可以转换为图表示形形式。Pyplot子模块的hist()函数将数据集数组和bins数组作为参数来创建相应数据值的直方图。
代码如下:
frommatplotlibimportpyplotasplt
importnumpyasnp
array3=np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27])
plt.hist(array3,bins=[0,20,40,60,80,100])
plt.title(histogram)
plt.show()
输出结果如图1W所示。
图1W使用Pyplot子模块的hist()函数绘制直方图