Python:matplotlib绘制直方图
使用hist方法来绘制直方图:
![](https://upload-images.jianshu.io/upload_images/13406307-10b316d01f631cec.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![](https://upload-images.jianshu.io/upload_images/13406307-1b870e54a7f73daf.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
绘制直方图,最主要的是一个数据集data和需要划分的区间数量bins,另外你也可以设置一些颜色、类型参数:
plt.hist(np.random.randn(1000), bins=30,normed=True, alpha=0.5, histtype='stepfilled', color='steelblue', edgecolor='none')
histtype直方图的类型,可以是'bar'、 'barstacked'、'step'和'stepfilled'。
有时候我们也会做一些直方对比图:
![](https://upload-images.jianshu.io/upload_images/13406307-63ee8261960123a9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![](https://upload-images.jianshu.io/upload_images/13406307-aadddbe0821fae14.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
除了一维的直方图,还可以使用hist2d方法绘制二维的直方图:
![](https://upload-images.jianshu.io/upload_images/13406307-b0ef34429e454dc4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![](https://upload-images.jianshu.io/upload_images/13406307-b01a860fed8fee9d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
hist2d是使用坐标轴正交的方块分割区域,还有一种常用的方式是正六边形也就是蜂窝形状的分割。Matplotlib提供的plt.hexbin就是满足这个需求的:
plt.hexbin(x,y,gridsize=30, cmap='Blues')
plt.colorbar(label='count in bin')
![](https://upload-images.jianshu.io/upload_images/13406307-a7cc8972c595fd5c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)