NumPy - 使用 Matplotlib 绘制直方图
NumPy 有一个 numpy.histogram() 函数,它可以以图形方式表示数据的频率分布。水平方向大小相等的矩形对应于类距,称为bin,高度变量对应于频率。
numpy.histogram()
numpy.histogram() 函数将输入数组和 bin 作为两个参数。 bin 数组中连续的元素充当每个 bin 的边界。
import numpy as np a = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27]) np.histogram(a,bins = [0,20,40,60,80,100]) hist,bins = np.histogram(a,bins = [0,20,40,60,80,100]) print hist print bins
将产生以下输出 -
[3 4 5 2 1] [0 20 40 60 80 100]
plt()
Matplotlib 可以将这种直方图的数值表示转换为图形。 pyplot 子模块的 plt() 函数 接收包含数据和 bin 数组的数组作为参数,并将其转换为直方图。
from matplotlib import pyplot as plt import numpy as np a = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27]) plt.hist(a, bins = [0,20,40,60,80,100]) plt.title("histogram") plt.show()
输出结果如下:
