用颜色在球体上表示数值
我有一组数据,对于离散的角度值theta和phi,我有一些对应的数值。我想把这些数值在一个球体上表示出来,也就是说在球体上某个点的颜色应该反映出这个特定的数值,这个点是由极角theta和方位角phi确定的。
我该如何在Python中实现这个呢?
1 个回答
1
我觉得这个 球面谐波的例子正是你需要的。
最简单的例子:
from mayavi import mlab import numpy as np # Make sphere, choose colors phi, theta = np.mgrid[0:np.pi:101j, 0:2*np.pi:101j] x, y, z = np.sin(phi) * np.cos(theta), np.sin(phi) * np.sin(theta), np.cos(phi) s = x*y # <-- colors # Display mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(600, 500)) mlab.mesh(x, y, z, scalars=s, colormap='Spectral') mlab.view() mlab.show()
- 你需要使用python2,而不是python3。可以看看这个 2015年的讨论。
在Ubuntu 14.04上,我说过:
sudo apt-get install python-vtk python-scipy python-numpy sudo pip install mayavi python main.py # After saving the code below as main.py
这是完整的代码:
# Author: Gael Varoquaux <gael.varoquaux@normalesup.org> # Copyright (c) 2008, Enthought, Inc. # License: BSD Style. from mayavi import mlab import numpy as np from scipy.special import sph_harm # Create a sphere r = 0.3 pi = np.pi cos = np.cos sin = np.sin phi, theta = np.mgrid[0:pi:101j, 0:2 * pi:101j] x = r * sin(phi) * cos(theta) y = r * sin(phi) * sin(theta) z = r * cos(phi) mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(400, 300)) mlab.clf() # Represent spherical harmonics on the surface of the sphere for n in range(1, 6): for m in range(n): s = sph_harm(m, n, theta, phi).real mlab.mesh(x - m, y - n, z, scalars=s, colormap='jet') s[s < 0] *= 0.97 s /= s.max() mlab.mesh(s * x - m, s * y - n, s * z + 1.3, scalars=s, colormap='Spectral') mlab.view(90, 70, 6.2, (-1.3, -2.9, 0.25)) mlab.show()
如果你的电脑比较慢,这个例子的加载时间大约需要20秒。
- 你可以用鼠标来旋转和缩放这个图像。