使用numpy和matplotlib库,可以使用histogram2d函数来计算直方图和将x,y轴数据分散到二维数组中。为了比较不同的直方图2D分箱,我们可以使用相同的边缘来生成这些直方图。
示例代码如下:
import numpy as np
import matplotlib.pyplot as plt
# 生成1000个随机数据点
x = np.random.normal(0, 1, 1000)
y = np.random.normal(0, 1, 1000)
# 定义边缘
bins = np.linspace(-4, 4, 50)
# 直方图2D分箱
h1, _, _ = np.histogram2d(x, y, bins=bins)
h2, _, _ = np.histogram2d(x, y, bins=[bins, bins/2])
# 绘制直方图2D
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(10,4))
ax1.imshow(h1.T, origin='lower')
ax1.set_title('Equal bins')
ax1.set_xlabel('X')
ax1.set_ylabel('Y')
ax2.imshow(h2.T, origin='lower')
ax2.set_title('Unequal bins')
ax2.set_xlabel('X')
ax2.set_ylabel('Y')
plt.show()
在上述示例中,我们先生成1000个随机数据点,然后定义边缘bins,并分别使用等间距和不等间距的边缘来生成直方图2D分箱。最后,使用imshow函数可视化结果。