Python:在曲面图上映射颜色

Python: mapping colors across surface plots

有没有办法将颜色方案从一个表面图映射到另一个表面图?

例如,假设我有:

    surf_1 = ax.plot_surface(X, Y, Z, cmap='summer')

    surf_2 = ax.plot_surface(X, Y, Z-Q, cmap='summer')

有没有办法将 Z-Q 定义的表面的配色方案映射到 Z 定义的表面?换句话说,我想可视化 surf_1,但我希望它的表面呈现 surf_2.

定义的颜色

对于上下文,我试图可视化围绕可变高度 (Q) 的参数 (Z) 波动的颜色,其中 Q 不一定等于 0。

编辑:有没有办法将 surf_2 中的颜色提取为数组,并将这些颜色用作 surf_1 的输入颜色?如有任何建议,我们将不胜感激!

您可以使用 ScalarMappable() 函数创建所有颜色以用作两个曲面图中的 facecolors。这是可运行的代码,演示了实现您想要的目标的步骤。

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

fig, ax = plt.subplots(subplot_kw={'projection': '3d'})
fig.set_size_inches([10, 8])

# Make up data for 2 surfaces
X = np.logspace(0, np.log10(16), 50)
Y = np.linspace(3, 6, 50)
Z = np.linspace(-1, 1, 50)
# Convert to 2d arrays
Z = np.outer(Z.T, Z)        # 50x50
X, Y = np.meshgrid(X, Y)    # 50x50

# Make use of `ScalarMappable()` for custom color
# This use Z to get a colormap for plotting the surface
C = np.linspace(-1, 1, Z.size).reshape(Z.shape)
colormap = "summer"   # 'inferno' 'plasma' 'viridis'
scmap = plt.cm.ScalarMappable(cmap=colormap)

# for clarity, 2 surfaces are separated by some z shift
zshift = 80

# Upper-surface
# Note: ax.plot_surface(X, Y, Z*X+zshift, cmap=colormap)
#  is almost equivalent with this
ax.plot_surface(X, Y, Z*X+zshift, facecolors=scmap.to_rgba(Z*X+zshift), shade=False)
# `shade=False` is used to suppress 3D shading

# Lower-surface
# Also use `facecolors=scmap.to_rgba(Z*X+zshift)`
# thus, equivalent with taking color from previous surface
ax.plot_surface(X, Y, Z, facecolors=scmap.to_rgba(Z*X+zshift), shade=False)

plt.show()

输出图: