我有两个数据集d1,d2
,其中填充了不同规模的2D数据。
import numpy as np
d1 = np.random.normal(-30,20,(500,2))
d2 = np.random.normal(-40,10,(500,2))
此外,我能够从每个单独的数据集创建单独的100 x 100
2D直方图(=灰度图像(。
bins = [100,100]
h1 = np.histogram2d(d1[:,0], d1[:,1], bins)[0]
h2 = np.histogram2d(d2[:,0], d2[:,1], bins)[0]
但在这种解决方案中,每个2D直方图都以其自身的平均值为中心,并且当将两个直方图绘制在彼此之上时。
我想要得到的是一个单独的100 x 100 x 2
直方图矩阵(相当于2通道图像(,它考虑了数据的不同比例,因此位移不会丢失。
如果将值bins=[100, 100]
传递给histogram2d
,则要求它在每个维度中自动计算100个bin。你可以自己做,所以这两个
bins = [
np.linspace(x.min(), x.max(), 100),
np.linspace(y.min(), y.max(), 100)
]
h1 = np.histogram2d(x, y, bins)
和
bins = [100, 100]
h1 = np.histogram2d(x, y, bins)
是等效的。
知道了这一点,我们现在可以计算两个阵列组合的bin范围,并使用这些
bins = [
np.linspace(
min(d1[:, 0].min(), d2[:, 0].min()),
max(d1[:, 0].max(), d2[:, 0].max()),
100
),
np.linspace(
min(d1[:, 1].min(), d2[:, 1].min()),
max(d1[:, 1].max(), d2[:, 1].max()),
100
)
]
h1 = np.histogram2d(d1[:,0], d1[:,1], bins)
h2 = np.histogram2d(d2[:,0], d2[:,1], bins)
或者将两个数据集堆叠在一起,并将代码简化一位
d = np.stack((d1, d2))
bins = [
np.linspace(d[..., 0].min(), d[..., 0].max(), 100),
np.linspace(d[..., 1].min(), d[..., 1].max(), 100),
]
h1 = np.histogram2d(d[0, :, 0], d[0, :, 1], bins)
h2 = np.histogram2d(d[1, :, 0], d[1, :, 1], bins)