加载中......
输入验证码,即可复制
微信扫码下载好向圈APP, 登陆后即可进入消息页面查看验证码
只需要3秒时间
一个直方图可以很好的把数据展示出来,Matplotlib库中plt.hist()函数用来展示直方图。这个函数的使用非常的简单,一行代码就可以创建一个直方图。

简单的直方图

import numpy as npimport matplotlib.pyplot as pltplt.style.use('seaborn-white')data = np.random.randn(1000)plt.hist(data)
掌握了Matplotlib这两个方法,轻松绘制出漂亮的直方图!-1.jpg

自定义直方图

hist()函数有很多参数,给我们优化默认参数带来的不足。
plt.hist(data, bins=30, density=True, alpha=0.5, histtype='stepfilled', color='steelblue', edgecolor='none')
掌握了Matplotlib这两个方法,轻松绘制出漂亮的直方图!-2.jpg

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)
掌握了Matplotlib这两个方法,轻松绘制出漂亮的直方图!-3.jpg

二维频次直方图

就像将一维数组分为区间创建一维频次直方图一样,我们也可以将二维数组按照二维区 间进行切分,来创建二维频次直方图。

1.plt.hist2d:二维频次直方图

绘制二维频次直方图最简单的方法,就是使用Matplotlib的plt.hist2d函数。
plt.hist2d(x, y, bins=30, cmap='Blues')cb = plt.colorbar()cb.set_label('counts in bin')
掌握了Matplotlib这两个方法,轻松绘制出漂亮的直方图!-4.jpg

2.plt.hexbin:六边形区间划分

二维频次直方图是由与坐标轴正交的方块分割而成的,还有一种常用的方式是用正六边形分割。Matplotlib 提供了 plt.hexbin 满足此类需求,将二维数据集分割成蜂窝状。
plt.hexbin(x, y, gridsize=30, cmap='Blues')cb = plt.colorbar(label='count in bin')
掌握了Matplotlib这两个方法,轻松绘制出漂亮的直方图!-5.jpg
C语言圈
7527 查看 4 0 反对

说说我的看法高级模式

您需要登录后才可以回帖 登录|立即注册

  • purple_蝎子

    2021-2-24 20:34:59 使用道具

    来自: 北京来自: 北京来自: 北京来自: 北京
    转发了
  • 冥觞i

    2021-2-25 23:42:35 使用道具

    来自: 中国来自: 中国来自: 中国来自: 中国
    转发了
  • ☆云紫音★

    2021-2-27 01:26:39 使用道具

    来自: 北京来自: 北京来自: 北京来自: 北京
    转发了
  • 水上之花

    2021-2-27 08:53:13 使用道具

    来自: 聚友网络来自: 聚友网络来自: 聚友网络来自: 聚友网络
    这个。。。只是转载。。原创在哪里?