原文:https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram2d.html
校对:(虚位以待)
numpy.
histogram2d
(x, y, bins=10, range=None, normed=False, weights=None)[source]计算两个数据样本的二维直方图。
参数: | x:array_like,shape(N,)
y:array_like,shape(N,)
bins:int或array_like或[int,int]或[数组,数组],可选
范围:array_like,shape(2,2),可选
normed:bool,可选
权限:array_like,shape(N,),可选
|
---|---|
返回: | H:ndarray,shape(nx,ny)
xedges:ndarray,shape(nx,)
yedges:ndarray,shape(ny)
|
也可以看看
histogram
histogramdd
笔记
When normed is True, then the returned histogram is the sample density, defined such that the sum over bins of the product bin_value * bin_area
is 1.
请注意,直方图不遵循笛卡尔约定,其中x值在横坐标上,而y值在纵坐标轴上。相反,x沿数组(垂直)的第一维直方图,沿数组(水平)的第二维直方图y。这可确保与histogramdd
的兼容性。
例子
>>> import matplotlib as mpl
>>> import matplotlib.pyplot as plt
构造具有可变bin宽度的2D直方图。首先定义bin边缘:
>>> xedges = [0, 1, 1.5, 3, 5]
>>> yedges = [0, 2, 3, 4, 6]
接下来我们创建一个带有随机bin内容的直方图H:
>>> x = np.random.normal(3, 1, 100)
>>> y = np.random.normal(1, 1, 100)
>>> H, xedges, yedges = np.histogram2d(y, x, bins=(xedges, yedges))
或者,我们用确定的bin内容填充直方图H:
>>> H = np.ones((4, 4)).cumsum().reshape(4, 4)
>>> print(H[::-1]) # This shows the bin content in the order as plotted
[[ 13. 14. 15. 16.]
[ 9. 10. 11. 12.]
[ 5. 6. 7. 8.]
[ 1. 2. 3. 4.]]
Imshow只能做一个等距表示的箱:
>>> fig = plt.figure(figsize=(7, 3))
>>> ax = fig.add_subplot(131)
>>> ax.set_title('imshow: equidistant')
>>> im = plt.imshow(H, interpolation='nearest', origin='low',
extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]])
pcolormesh可以显示确切的边框:
>>> ax = fig.add_subplot(132)
>>> ax.set_title('pcolormesh: exact bin edges')
>>> X, Y = np.meshgrid(xedges, yedges)
>>> ax.pcolormesh(X, Y, H)
>>> ax.set_aspect('equal')
NonUniformImage通过插值显示精确边框:
>>> ax = fig.add_subplot(133)
>>> ax.set_title('NonUniformImage: interpolated')
>>> im = mpl.image.NonUniformImage(ax, interpolation='bilinear')
>>> xcenters = xedges[:-1] + 0.5 * (xedges[1:] - xedges[:-1])
>>> ycenters = yedges[:-1] + 0.5 * (yedges[1:] - yedges[:-1])
>>> im.set_data(xcenters, ycenters, H)
>>> ax.images.append(im)
>>> ax.set_xlim(xedges[0], xedges[-1])
>>> ax.set_ylim(yedges[0], yedges[-1])
>>> ax.set_aspect('equal')
>>> plt.show()
(源代码)