在 3D 图中绘制所有三个轴上的分布等值线

Plot contours of distribution on all three axes in 3D plot

我在三维 space 中有一团点,并估计了这些点的一些分布(也在 3D space 中;使用 kernel density estimation 尽管这与此无关题)。我想将该分布的投影作为等高线图绘制到所有三个轴(x、y 和 z)上。对 z 轴执行此操作很简单(即投影到各处具有相同 z 坐标的平面):

import numpy as np
import scipy as sp
import scipy.stats
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d

# generate some points of a 3D Gaussian
points = np.random.normal(size=(3, 50))

# do kernel density estimation to get smooth estimate of distribution
# make grid of points
x, y, z = np.mgrid[-4:4:100j, -4:4:100j, -4:4:100j]
kernel = sp.stats.gaussian_kde(points)
positions = np.vstack((x.ravel(), y.ravel(), z.ravel()))
density = np.reshape(kernel(positions).T, x.shape)

# now density is 100x100x100 ndarray

# plot points
ax = plt.subplot(projection='3d')
ax.plot(points[0,:], points[1,:], points[2,:], 'o')

# plot projection of density onto z-axis
plotdat = np.sum(density, axis=2)
plotdat = plotdat / np.max(plotdat)
plotx, ploty = np.mgrid[-4:4:100j, -4:4:100j]
ax.contour(plotx, ploty, plotdat, offset=-4)

ax.set_xlim((-4, 4))
ax.set_ylim((-4, 4))
ax.set_zlim((-4, 4))

但是,对其他轴执行此操作似乎未在 Matplotlib 中实现。如果我使用 this example 中概述的方法并指定 zdir 关键字参数:

# plot projection of density onto x-axis
plotdat = np.sum(density, axis=0)
plotdat = plotdat / np.max(plotdat)
ploty, plotz = np.mgrid[-4:4:100j, -4:4:100j]
ax.contour(ploty, plotz, plotdat, offset=-4, zdir='x')

轮廓生成完成'along another slice',也就是说:

而我想要这样的东西(糟糕的绘画技巧;希望思路清晰):

我想到的一个选项是沿默认 zdir='z' 生成轮廓,然后在 3D 中旋转生成的曲线 space,但我不知道如何处理。如果有任何指点,我将不胜感激!

我试图通过将计算为沿轴总和的数据与 np.mgrid 创建的网格混合来修改等高线图。我计算了沿我想要轮廓的轴的密度总和。这看起来如下:

# plot projection of density onto z-axis
plotdat = np.sum(density, axis=2)
plotdat = plotdat / np.max(plotdat)
plotx, ploty = np.mgrid[-4:4:100j, -4:4:100j]
ax.contour(plotx, ploty, plotdat, offset=-4, zdir='z')

#This is new
#plot projection of density onto y-axis
plotdat = np.sum(density, axis=1) #summing up density along y-axis
plotdat = plotdat / np.max(plotdat)
plotx, plotz = np.mgrid[-4:4:100j, -4:4:100j]
ax.contour(plotx, plotdat, plotz, offset=4, zdir='y')

#plot projection of density onto x-axis
plotdat = np.sum(density, axis=0) #summing up density along z-axis
plotdat = plotdat / np.max(plotdat)
ploty, plotz = np.mgrid[-4:4:100j, -4:4:100j]
ax.contour(plotdat, ploty, plotz, offset=-4, zdir='x')
#continue with your code

不幸的是,我对核密度估计不是很熟悉,所以我希望我没有理解完全错误的东西,但是如果你添加上面的几行代码生成的结果看起来与你的花式绘画图片相似: )