1、简单的频次直方图:
plt.hist()文档:https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.hist.html#matplotlib.pyplot.hist
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('seaborn-white')
data = np.random.randn(1000)
plt.hist(data)
自定义的频次直方图:
plt.hist(data, bins=30, normed=True, alpha=0.5, histtype='stepfilled',
color='steelblue', edgecolor='none')
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, normed=True, bins=40)
plt.hist(x1, **kwargs)
plt.hist(x2, **kwargs)
plt.hist(x3, **kwargs)
如果想要简单的计算每段区间的样本数,可以直接用 np.histogram():
https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html
>>>counts, bin_edgs = np.histogram(data, bins=5)
>>>print(counts)
[ 23 292 499 171 15]
>>>print(bin_edgs) # 返回bin的边缘
[-3.20401671 -1.85158271 -0.4991487 0.85328531 2.20571931 3.55815332]
二、二维频次直方图与数据划分
1、plt.hist2d: 二维频次直方图
https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.hist2d.html#matplotlib.pyplot.hist2d
mean = [0, 0]
cov = [[1, 1], [1, 2]]
x, y = np.random.multivariate_normal(mean, cov, 10000).T
plt.hist2d(x, y, bins=30, cmap='Blues')
cb = plt.colorbar()
cb.set_label('counts in bin')
与plt.hist() 函数一样,plt.hist2d 也有许多调整图形与区间划分的配置选项。
2、plt.hexbin: 六边形区间划分
二维频次直方图是由与坐标轴正交的方块分割而成的,还有一种常用的方式是用正六边形分割。
plt.hexbin(x, y, gridsize=30, cmap='Blues')
cb = plt.colorbar(label='count in bin')