您可以使用numpy.histogramdd(sample) 执行此操作,其中每个方向的 bin 数量和物理范围可以像使用一维直方图一样进行调整。有关参考 page 的更多信息。对于更一般的统计数据,例如 bin 中每个点的另一个变量的平均值,您可以使用 scipy scipy.stats.binned_statistic_dd 函数,请参阅 docs。
对于具有三维点数组的情况,您可以通过以下方式使用它,
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from scipy import stats
#Setup some dummy data
points = np.random.randn(1000,3)
hist, binedges = np.histogramdd(points, normed=False)
#Setup a 3D figure and plot points as well as a series of slices
fig = plt.figure()
ax1 = fig.add_subplot(111, projection='3d')
ax1.plot(points[:,0],points[:,1],points[:,2],'k.',alpha=0.3)
#Use one less than bin edges to give rough bin location
X, Y = np.meshgrid(binedges[0][:-1],binedges[1][:-1])
#Loop over range of slice locations (default histogram uses 10 bins)
for ct in [0,2,5,7,9]:
cs = ax1.contourf(X,Y,hist[:,:,ct],
zdir='z',
offset=binedges[2][ct],
level=100,
cmap=plt.cm.RdYlBu_r,
alpha=0.5)
ax1.set_xlim(-3, 3)
ax1.set_ylim(-3, 3)
ax1.set_zlim(-3, 3)
plt.colorbar(cs)
plt.show()
它给出了每个位置占用率的一系列直方图切片,