【问题标题】:Colouring the surface of a sphere with a set of scalar values in matplotlib在 matplotlib 中使用一组标量值对球体的表面进行着色
【发布时间】:2014-08-04 19:02:57
【问题描述】:

我对 matplotlib 比较陌生(这也是我在这里的第一个问题)。我试图代表脑电图记录的头皮表面电位。到目前为止,我有一个球体投影的二维图形,它是使用 contourf 生成的,并且几乎可以归结为一个普通的热图。

有什么方法可以在半个球体上完成吗?即生成一个 3D 球体,其表面颜色由值列表给出?像这样的东西,http://embal.gforge.inria.fr/img/inverse.jpg,但我只有半个球体就足够了。

我看到了一些相关问题(例如,Matplotlib 3d colour plot - is it possible?),但它们要么没有真正解决我的问题,要么至今仍未得到解答。

我还花了一上午的时间浏览了无数的例子。在我发现的大部分内容中,表面某个特定点的颜色表示其 Z 值,但我不希望这样......我想绘制表面,然后用我的数据指定颜色有。

【问题讨论】:

    标签: python-2.7 matplotlib plot


    【解决方案1】:

    您可以使用plot_trisurf 并通过set_array 方法将自定义字段分配给底层ScalarMappable

    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()
    

    【讨论】:

    • 谢谢。它现在不起作用,但我认为这是因为我使用的是 1.1.1 版本。我会尝试升级,如果这是问题,我会立即接受您的回答。
    • 以防万一将来有人遇到同样的问题,这个解决方案确实需要最新(截至目前为 1.3.1)版本的 matplotlib。此外,有什么方法可以让颜色不成为位置的函数?我一直在尝试将值列表传递给您的解决方案,但我无法使其工作。
    • 感谢您的精确。关于您的问题,确实有可能:只需将大小为 ntri(三角形数)的一维数组传递给collec.set_array。如果您只知道节点值,则必须按三角形对它们进行平均,这就是我在代码块“#Defining a custom color scalar field”中所做的。还是我缺少什么?
    • 不错的答案 - 但是当三角形的数量很大(比如大约 70,000 个)时,我遇到了问题,在这种情况下,我的计算机在尝试绘图时出现某种内存问题,程序死掉了。跨度>
    • 非常感谢!这个collec.set_array(colors) 就像魔术一样!
    猜你喜欢
    • 1970-01-01
    • 2011-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-09
    相关资源
    最近更新 更多