python - 如何在 matplotlib 的 3D 曲面图中将颜色显示为与原点的距离的函数?
问题描述
我正在尝试使用 python 的 matplotlib 包在球坐标中绘制某个函数 Q(theta, phi)。我希望颜色显示为与原点的距离而不是 z 坐标的函数。有没有办法做到这一点?这是我用来生成 3D 曲面图的代码:
%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()
我没有赢得足够的声誉来发布我创建的情节。它类似于此链接中的图:https ://matplotlib.org/3.1.1/gallery/mplot3d/surface3d.html 。如您所见,颜色是 z 坐标的函数,而不是与原点的距离的函数。
解决方案
您应该指定facecolor
in plot_surface
,而不是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))
推荐阅读
- api - 如果 graphql 是一种查询语言,为什么它用在前端而不是后端?
- apify - PuppeteerCrawler 和 Task 的 Settigs 差异
- oracle - PLS-00103:结束而不是编译指示最终实例化顺序覆盖静态成员构造函数映射
- java - JSP 代码超出了 65535 字节的限制 - Tomcat 9 修复
- android - 只要应用程序打开,如何使用socket.io保持活跃的android webview
- java - 哪些声明是有效的?
- php - Foreach 循环和 cURL 请求的问题
- json - 在句子(句子数组)中的任何位置找到确切的两个单词 elastcsearch 6.8
- c# - 如何在 Unity 上的 Google OnAdclose 上访问从一个 GameObject 到另一个 GameObject 的方法?
- laravel-5 - 数据表 - 用图标替换值适用于一个单元格而不是两个单元格