在3D绘图中绘制所有三个轴上的分布轮廓

时间:2016-04-18 17:08:32

标签: python matplotlib plot 3d mplot3d

我在三维空间中有一堆点,并估计了这些点上的一些分布(也在3D空间中;使用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))

Projection of contours onto z-axis

但是,对其他轴执行此操作似乎未在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')

轮廓的生成是沿着另一个切片完成的,所以说:

enter image description here

虽然我想要这样的东西(糟糕的油漆技能;希望这个想法很明确):

enter image description here

我想到的一个选项是沿默认zdir='z'生成轮廓,然后在3D空间中旋转生成的曲线,但我不知道如何处理它。我会非常感谢任何指针!

1 个答案:

答案 0 :(得分:4)

我试图通过将计算为轴的和的数据与name e_point n_point David 102 345 James 174 746 Ali 460 584 Kevin 364 479 Mark 385 274 创建的网格混合来修改等值线图。我计算了沿着我想要轮廓的轴的密度之和。这看起来如下:

np.mgrid

不幸的是我对内核密度估计并不是很熟悉,所以我希望我不明白完全错误但是如果你在上面添加几行代码就产生的结果看起来与你想象的油漆图片相似:) { {3}}