bin 3d指向在Python的3d容器

时间:2015-10-01 15:05:16

标签: python multidimensional-array binning

如何将3d点分成3d箱?是否有np.digitize的多维版本? 我可以为每个维度单独使用np.digitize,例如here。有更好的解决方案吗? 谢谢!

1 个答案:

答案 0 :(得分:4)

您可以使用numpy.histogramdd(sample)执行此操作,其中每个方向的容器数量和物理范围可以使用1D直方图进行调整。有关参考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()

给出了每个位置的一系列直方图切片,

enter image description here