建立在user1415946的评论基础上,你可以假设每个点代表一个
双变量正态分布,其协方差矩阵由
[[e_x[i]**2,0][0,e_y[i]**2]]
给出。但是,所得到的分布不是正态分布 - 在运行示例后,你会发现直方图根本不像高斯分布,而是一组它们。
创建此分布集合的直方图的一种方法是使用
numpy.random.multivariate_normal从每个点生成随机样本。看下面的示例代码,其中包含一些人工数据。
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
def plotHistogram3d(hist, xedges, yedges):
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
hist = hist.transpose()
dx = np.mean(np.diff(xedges))
dy = np.mean(np.diff(yedges))
elements = (len(xedges) - 1) * (len(yedges) - 1)
xpos, ypos = np.meshgrid(xedges[:-1]+dx/2.0, yedges[:-1]+dy/2.0)
xpos = xpos.flatten()
ypos = ypos.flatten()
zpos = np.zeros(elements)
dx = dx * np.ones_like(zpos) * 0.5
dy = dy * np.ones_like(zpos) * 0.5
dz = hist.flatten()
ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('Count')
return
"""
INPUT DATA
"""
data = np.array([[1, 2, 1, 1, 1],
[3, 0, 1, 1, 2],
[0, 1, 2, 1, 5],
[7, 7, 1, 3, 1]])
"""
Generate samples
"""
SAMPLE_SIZE = 100
points = np.zeros((SAMPLE_SIZE * data.shape[0], 3))
for i, element in enumerate(data):
meanVector = element[:2]
covarianceMatrix = np.diag(element[2:4]**2)
points[SAMPLE_SIZE*i:SAMPLE_SIZE*(i+1), :2] = \
np.random.multivariate_normal(meanVector, covarianceMatrix, SAMPLE_SIZE)
points[SAMPLE_SIZE*i:SAMPLE_SIZE*(i+1), 2] = element[4]
hist, xedges, yedges = np.histogram2d(points[:, 0], points[:, 1], weights=points[:, 2])
plotHistogram3d(hist, xedges, yedges)
plt.show()
下面绘制的结果如下:
![enter image description here](https://istack.dev59.com/Xnloe.webp)