使用matplotlib中的一组标量值为球体表面着色

时间:2014-06-14 09:30:36

标签: python-2.7 matplotlib plot

我对matplotlib很新(这也是我的第一个问题)。我试图表示脑电图记录的头皮表面电位。到目前为止,我有一个球体投影的二维图形,我使用contourf生成,几乎归结为普通的热图。

有没有办法可以在半个球体上完成?,即生成一个由一系列值给出的表面颜色的3D球体?这样的事情,http://embal.gforge.inria.fr/img/inverse.jpg,但我只有半个球体就足够了。

我已经看到了一些相关的问题(例如,Matplotlib 3d colour plot - is it possible?),但他们要么没有真正解决我的问题,要么到目前为止仍然没有答案。

我早上也花了很多时间来看看。在我发现的大部分内容中,表面某个特定点的颜色表示其Z值,但我不想要...我想绘制表面,然后指定颜色用我的数据。

1 个答案:

答案 0 :(得分:5)

您可以使用plot_trisurf并为基础ScalarMappableset_array方法指定自定义字段。

import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import matplotlib.tri as mtri

(n, m) = (250, 250)

# Meshing a unit sphere according to n, m 
theta = np.linspace(0, 2 * np.pi, num=n, endpoint=False)
phi = np.linspace(np.pi * (-0.5 + 1./(m+1)), np.pi*0.5, num=m, endpoint=False)
theta, phi = np.meshgrid(theta, phi)
theta, phi = theta.ravel(), phi.ravel()
theta = np.append(theta, [0.]) # Adding the north pole...
phi = np.append(phi, [np.pi*0.5])
mesh_x, mesh_y = ((np.pi*0.5 - phi)*np.cos(theta), (np.pi*0.5 - phi)*np.sin(theta))
triangles = mtri.Triangulation(mesh_x, mesh_y).triangles
x, y, z = np.cos(phi)*np.cos(theta), np.cos(phi)*np.sin(theta), np.sin(phi)

# Defining a custom color scalar field
vals = np.sin(6*phi) * np.sin(3*theta)
colors = np.mean(vals[triangles], axis=1)

# Plotting
fig = plt.figure()
ax = fig.gca(projection='3d')
cmap = plt.get_cmap('Blues')
triang = mtri.Triangulation(x, y, triangles)
collec = ax.plot_trisurf(triang, z, cmap=cmap, shade=False, linewidth=0.)
collec.set_array(colors)
collec.autoscale()
plt.show()

enter image description here