numpy.histogram2d#

numpy.histogram2d(x, y, bins=10, range=None, density=None, weights=None)[源代码]#

计算两个数据样本的双维直方图。

参数:
xarray_like, shape (N,)

包含要进行直方图统计的点 x 坐标的数组。

yarray_like, shape (N,)

包含要进行直方图统计的点 y 坐标的数组。

binsint 或 array_like 或 [int, int] 或 [array, array],可选

bin 的规格

  • 如果是整数,则表示两个维度的 bin 数量(nx=ny=bins)。

  • 如果是 array_like,则表示两个维度的 bin 边界(x_edges=y_edges=bins)。

  • 如果是 [int, int],则表示每个维度的 bin 数量(nx, ny = bins)。

  • 如果是 [array, array],则表示每个维度的 bin 边界(x_edges, y_edges = bins)。

  • 可以是 [int, array] 或 [array, int] 的组合,其中 int 是 bin 数量,array 是 bin 边界。

rangearray_like, shape(2,2),可选

沿每个维度的 bin 的最左边和最右边的边界(如果在 bins 参数中未明确指定):[[xmin, xmax], [ymin, ymax]]。此范围之外的所有值都将被视为异常值,不会在直方图中统计。

densitybool,可选

如果为 False(默认值),则返回每个 bin 中的样本数。如果为 True,则返回 bin 处的概率密度函数,即bin_count / sample_count / bin_area

weightsarray_like, shape(N,), 可选

一个值数组 w_i,用于加权每个样本 (x_i, y_i)。如果 density 为 True,则权重将归一化为 1。如果 density 为 False,则返回的直方图的值等于落入每个 bin 的样本的权重之和。

返回:
Hndarray, shape(nx, ny)

样本 xy 的双维直方图。沿第一个维度的 x 中的值进行直方图统计,沿第二个维度的 y 中的值进行直方图统计。

xedgesndarray, shape(nx+1,)

沿第一个维度的 bin 边界。

yedgesndarray, shape(ny+1,)

沿第二个维度的 bin 边界。

另请参阅

histogram

一维直方图

histogramdd

多维直方图

备注

density 为 True 时,返回的直方图是样本密度,定义为 bin 值与 bin 面积的乘积在 bin 上的总和为 1。

请注意,直方图不遵循笛卡尔坐标约定,即 x 值在横轴上,y 值在纵轴上。相反,x 沿数组的第一个维度(垂直)进行直方图统计,y 沿数组的第二个维度(水平)进行直方图统计。这确保了与 histogramdd 的兼容性。

示例

>>> import numpy as np
>>> from matplotlib.image import NonUniformImage
>>> import matplotlib.pyplot as plt

构造具有可变 bin 宽度的二维直方图。首先定义 bin 边界

>>> xedges = [0, 1, 3, 5]
>>> yedges = [0, 2, 3, 4, 6]

接下来我们创建一个内容随机的直方图 H

>>> x = np.random.normal(2, 1, 100)
>>> y = np.random.normal(1, 1, 100)
>>> H, xedges, yedges = np.histogram2d(x, y, bins=(xedges, yedges))
>>> # Histogram does not follow Cartesian convention (see Notes),
>>> # therefore transpose H for visualization purposes.
>>> H = H.T

imshow 只能显示方形 bin

>>> fig = plt.figure(figsize=(7, 3))
>>> ax = fig.add_subplot(131, title='imshow: square bins')
>>> plt.imshow(H, interpolation='nearest', origin='lower',
...         extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]])
<matplotlib.image.AxesImage object at 0x...>

pcolormesh 可以显示实际的边界

>>> ax = fig.add_subplot(132, title='pcolormesh: actual edges',
...         aspect='equal')
>>> X, Y = np.meshgrid(xedges, yedges)
>>> ax.pcolormesh(X, Y, H)
<matplotlib.collections.QuadMesh object at 0x...>

NonUniformImage 可用于显示具有插值的实际 bin 边界

>>> ax = fig.add_subplot(133, title='NonUniformImage: interpolated',
...         aspect='equal', xlim=xedges[[0, -1]], ylim=yedges[[0, -1]])
>>> im = NonUniformImage(ax, interpolation='bilinear')
>>> xcenters = (xedges[:-1] + xedges[1:]) / 2
>>> ycenters = (yedges[:-1] + yedges[1:]) / 2
>>> im.set_data(xcenters, ycenters, H)
>>> ax.add_image(im)
>>> plt.show()
../../_images/numpy-histogram2d-1_00_00.png

也可以构造一个不指定 bin 边界的二维直方图

>>> # Generate non-symmetric test data
>>> n = 10000
>>> x = np.linspace(1, 100, n)
>>> y = 2*np.log(x) + np.random.rand(n) - 0.5
>>> # Compute 2d histogram. Note the order of x/y and xedges/yedges
>>> H, yedges, xedges = np.histogram2d(y, x, bins=20)

现在我们可以使用 pcolormesh 绘制直方图,并进行 hexbin 比较。

>>> # Plot histogram using pcolormesh
>>> fig, (ax1, ax2) = plt.subplots(ncols=2, sharey=True)
>>> ax1.pcolormesh(xedges, yedges, H, cmap='rainbow')
>>> ax1.plot(x, 2*np.log(x), 'k-')
>>> ax1.set_xlim(x.min(), x.max())
>>> ax1.set_ylim(y.min(), y.max())
>>> ax1.set_xlabel('x')
>>> ax1.set_ylabel('y')
>>> ax1.set_title('histogram2d')
>>> ax1.grid()
>>> # Create hexbin plot for comparison
>>> ax2.hexbin(x, y, gridsize=20, cmap='rainbow')
>>> ax2.plot(x, 2*np.log(x), 'k-')
>>> ax2.set_title('hexbin')
>>> ax2.set_xlim(x.min(), x.max())
>>> ax2.set_xlabel('x')
>>> ax2.grid()
>>> plt.show()
../../_images/numpy-histogram2d-1_01_00.png