[英]How to display color as a function of distance to the origin in matplotlib's 3D surface plot?
I am trying to plot a certain function Q(theta, phi) in spherical coordinate using python's matplotlib package. I want the color to show up as a function of distance to the origin instead of the z coordinate.我正在尝试使用 python 的 matplotlib package 在球坐标中 plot 某个 function Q(theta, phi)。我希望颜色显示为到原点的距离 function 而不是 z 坐标。 Is there a way to do this?有没有办法做到这一点? Here is the code I use to produce the 3D surface plot:这是我用来生成 3D 表面 plot 的代码:
%matplotlib notebook
fig = plt.figure(figsize=(12,12))
ax = fig.add_subplot(111, projection='3d')
X, Y = Q*np.sin(Theta)*np.cos(Phi), Q*np.sin(Theta)*np.sin(Phi)
Z = Q*np.cos(Theta)
ax.plot_surface(X, Y, Z, cmap=plt.cm.YlGnBu_r)
ax.set_zlim(-1, 1)
ax.set_ylim(-1, 1)
ax.set_xlim(-1, 1)
ax.set_xlabel('J_x')
ax.set_ylabel('J_y')
ax.set_zlabel('J_z')
plt.show()
I have not earned enough reputations to post the plot I created.我没有赢得足够的声誉来发布我创建的 plot。 It is similar to the plot in this link: https://matplotlib.org/3.1.1/gallery/mplot3d/surface3d.html .它类似于此链接中的 plot: https://matplotlib.org/3.1.1/gallery/mplot3d/surface3d.html 。 As you can see, the color is a function of the z coordinate, not of the distance from the origin.如您所见,颜色是 function 的 z 坐标,而不是距原点的距离。
You should specify facecolor
in plot_surface
, not cmap
.您应该在plot_surface
中指定facecolor
,而不是cmap
。
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
# Make data.
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)
Z = np.sin(R)
d = np.sqrt(X**2+Y**2+Z**2)
d = d/d.max()
# Plot the surface with face colors taken from the array we made.
surf = ax.plot_surface(X, Y, Z, facecolors=plt.cm.viridis(d), linewidth=0)
# Customize the z axis.
ax.set_zlim(-1, 1)
ax.w_zaxis.set_major_locator(LinearLocator(6))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.