简体   繁体   English

3d 表面上的 Matplotlib plot 轮廓

[英]Matplotlib plot contourf on 3d surface

I am trying to use the colormap feature of a 3d-surface plot in matplotlib to color the surface based on values from another array instead of the z-values.我正在尝试在 matplotlib 中使用 3d 表面 plot 的颜色图功能来根据来自另一个数组的值而不是 z 值对表面进行着色。 The surface plot is created and displayed as follows:曲面 plot 创建并显示如下:

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

def gauss(x, y, w_0):
    r = np.sqrt(x**2 + y**2)
    return np.exp(-2*r**2 / w_0**2)


x = np.linspace(-100, 100, 100)
y = np.linspace(-100, 100, 100)
X, Y = np.meshgrid(x, y)
Z = gauss(X, Y, 50)
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.plot_surface(X, Y, Z, cmap='jet')

Now instead of coloring based on elevation of the 3d-surface, I am looking to supply the color data for the surface in form of another array, here as an example a random one:现在,我不是基于 3d 表面的高程进行着色,而是希望以另一个数组的形式提供表面的颜色数据,这里以随机数组为例:

color_data = np.random.uniform(0, 1, size=(Z.shape))

However, I did not find a solution to colorize the 3d-surface based on those values.但是,我没有找到基于这些值对 3d 表面着色的解决方案。 Ideally, it would look like a contourf plot in 3d, just on the 3d surface.理想情况下,它看起来像 3d 中的轮廓 plot,就在 3d 表面上。

You can use matplotlib.colors.from_levels_and_colors to obtain a colormap and normalization, then apply those to the values to be colormapped.您可以使用matplotlib.colors.from_levels_and_colors来获取颜色图和归一化,然后将它们应用于要进行颜色映射的值。

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

x = np.linspace(-100, 100, 101)
y = np.linspace(-100, 100, 101)
X, Y = np.meshgrid(x, y)
Z = np.exp(-2*np.sqrt(X**2 + Y**2)**2 / 50**2)

c = X+50*np.cos(Y/20)  # values to be colormapped
N = 11                 # Number of level (edges) 
levels = np.linspace(-150,150,N)
colors = plt.cm.get_cmap("RdYlGn", N-1)(np.arange(N-1))
cmap, norm = matplotlib.colors.from_levels_and_colors(levels, colors)
color_vals = cmap(norm(c))

fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.plot_surface(X, Y, Z, facecolors=color_vals, rstride=1, cstride=1)
plt.show()

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM