Eel*_*aak 6 python 3d plot matplotlib mplot3d
我在三维空间中有一堆点,并估计了这些点上的一些分布(也在3D空间中;使用核密度估计,尽管这与此问题无关).我想将该分布的投影绘制为所有三个轴(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))
Run Code Online (Sandbox Code Playgroud)
但是,对其他轴执行此操作似乎未在Matplotlib中实现.如果我使用此示例中概述的方法,并指定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')
Run Code Online (Sandbox Code Playgroud)
轮廓的生成是"沿另一个切片"完成的,所以说:
虽然我想要这样的东西(糟糕的油漆技能;希望这个想法很清楚):
我想到的一个选择是沿着默认值生成轮廓zdir='z',然后在3D空间中旋转生成的曲线,但我不知道如何处理它.我会非常感谢任何指针!
我试图通过将计算为沿轴的总和计算的数据与由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
Run Code Online (Sandbox Code Playgroud)
不幸的是,我对内核密度估计不是很熟悉,所以我希望我没有理解完全错误的东西,但是如果添加上面几行代码生成的结果看起来与您喜欢的绘画图片相似:) 