matplotlib中的距离依赖着色
我想制作一些关于电磁散射过程的远场图。
为此,我计算了θ、φ和r的值。θ和φ这两个坐标在单位球面上形成了一个规则的网格,所以我可以使用plot_Surface
(在这里可以找到)并将其转换为笛卡尔坐标。
我现在的问题是,我需要一种方法来根据半径r来给表面上色,而不是默认的高度z。
有没有办法改变这个依赖关系呢?
1 个回答
2
我不知道你现在进展如何,也许你已经解决了这个问题。不过,根据保罗评论中的链接,你可以尝试这样做。我们可以通过plot_surface的facecolor参数来传递我们想要的颜色值。
(我修改了matplotlib文档中的surface3d示例)
编辑:正如斯特凡在评论中提到的,我的答案可以简化为:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-5, 5, 0.25)
xlen = len(X)
Y = np.arange(-5, 5, 0.25)
ylen = len(Y)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
maxR = np.amax(R)
Z = np.sin(R)
# Note that the R values must still be normalized.
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, facecolors=cm.jet(R/maxR),
linewidth=0)
plt.show()
而且(这是)我原本复杂的版本的结尾,使用的代码和上面一样,只是省略了matplotlib.cm的导入。
# We will store (R, G, B, alpha)
colorshape = R.shape + (4,)
colors = np.empty( colorshape )
for y in range(ylen):
for x in range(xlen):
# Normalize the radial value.
# 'jet' could be any of the built-in colormaps (or your own).
colors[x, y] = plt.cm.jet(R[x, y] / maxR )
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, facecolors=colors,
linewidth=0)
plt.show()