一个直方图可以很好的把数据展示出来,Matplotlib库中plt.hist()函数用来展示直方图。这个函数的使用非常的简单,一行代码就可以创建一个直方图。
简单的直方图
import numpy as npimport matplotlib.pyplot as pltplt.style.use('seaborn-white')data = np.random.randn(1000)plt.hist(data)
自定义直方图
hist()函数有很多参数,给我们优化默认参数带来的不足。
plt.hist(data, bins=30, density=True, alpha=0.5, histtype='stepfilled', color='steelblue', edgecolor='none')
plt.hist()参数设置
arr: 需要计算直方图的一维数组;bins: 直方图的柱数,可选项,默认为10;density: : 是否将得到的直方图向量归一化。默认为0;color:颜色序列,默认为None;facecolor: 直方图颜色;edgecolor: 直方图边框颜色;alpha: 透明度;histtype: 直方图类型,‘bar’, ‘barstacked’, ‘step’, ‘stepfilled’;
同坐标轴的多个频次直方图
x1 = np.random.normal(0, 0.8, 1000)x2 = np.random.normal(-2, 1, 1000)x3 = np.random.normal(3, 2, 1000)kwargs = dict(histtype='stepfilled', alpha=0.3, density=True, bins=40)plt.hist(x1, **kwargs)plt.hist(x2, **kwargs)plt.hist(x3, **kwargs)
二维频次直方图
就像将一维数组分为区间创建一维频次直方图一样,我们也可以将二维数组按照二维区 间进行切分,来创建二维频次直方图。
1.plt.hist2d:二维频次直方图
绘制二维频次直方图最简单的方法,就是使用Matplotlib的plt.hist2d函数。
plt.hist2d(x, y, bins=30, cmap='Blues')cb = plt.colorbar()cb.set_label('counts in bin')
2.plt.hexbin:六边形区间划分
二维频次直方图是由与坐标轴正交的方块分割而成的,还有一种常用的方式是用正六边形分割。Matplotlib 提供了 plt.hexbin 满足此类需求,将二维数据集分割成蜂窝状。
plt.hexbin(x, y, gridsize=30, cmap='Blues')cb = plt.colorbar(label='count in bin')