如何在Matplotlib 3D表面图中突出显示切片?

5

我有一个3D表面图。我还想在2D中绘制这个图的切片,并在3D图中某些位置指示切片来自哪里(例如,将沿着切片的点着色以“突出”切片,或绘制相交的平面等)。

以下是一个示例,其中我只是将特定行设置为0,以便在3D图上看到切片的位置。

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


# Grid and test function
N = 29;
x,y = np.linspace(-1,1, N*2), np.linspace(-1,1, N)
X,Y = np.meshgrid(x,y)
F = lambda X,Y : np.sin(10*X)/(1+5*(X**2+Y**2))
Z = F(X,Y)

# 3D Surface plot
plt.figure(figsize = (5,6))
Z2 = Z.copy(); Z2[10,:] = 0 # <----- Replace this code
ax = plt.subplot(211, projection='3d')
ax.plot_surface(X,Y,Z2)

# 2D Plot of slice of 3D plot 
plt.subplot(212)
plt.plot(x,Z[10,:])
plt.show()

plt.savefig('surfacePlotHighlight.png')

3D surface plot and 2D slice

2个回答

2
你可以使用 plot_surface 中的 facecolor 选项在 X 或 Y 方向上着色,以及在 plot 中设置类似的颜色。例如:

Original Answer 可以翻译为 "最初的回答"。

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

# Grid and test function
N = 29;
x,y = np.linspace(-1,1, N*2), np.linspace(-1,1, N)
X,Y = np.meshgrid(x,y)
F = lambda X,Y : np.sin(10*X)/(1+5*(X**2+Y**2))
Z = F(X,Y)

# 3D Surface plot
plt.figure(figsize = (5,6))
ax = plt.subplot(211, projection='3d')
# Normalise Y for calling in the cmap.
Ys = Y/Y.max()
cmap = plt.cm.viridis
ax.plot_surface(X, Y, Z2, facecolors=cmap(Ys))

# 2D Plot of slice of 3D plot 
# Normalise y for calling in the cmap.
ys = y/y.max()
plt.subplot(212)
plt.plot(x,Z[10,:], color=cmap(ys[10]))
plt.plot(x,Z[20,:], color=cmap(ys[20]))
plt.show()

plt.savefig('surfacePlotHighlight.png')

"最初的回答"

这里输入图片描述

编辑: 通过编辑颜色数组来突出显示单行(或列,或任意一组点),例如:

# 3D Surface plot
plt.figure(1,figsize = (5,6))
ax = plt.subplot(211, projection='3d')
# Create array to specify color of each pixel on surface
Ys = Y*0
Ys[:,:] = .3
Ys[10] = 1
Ys[20] = .7
cmap = plt.cm.viridis
ax.plot_surface(X, Y, Z, facecolors=cmap(Ys))

# 2D Plot of slice of 3D plot 
# Normalise y for calling in the cmap.
ys = Ys[:,0]
plt.subplot(212)
plt.plot(x,Z[10,:], color=cmap(ys[10]))
plt.plot(x,Z[20,:], color=cmap(ys[20]))
plt.show()

plt.savefig('surfacePlotHighlight.png')

enter image description here


谢谢,这让我完成了90%。你介意我在你的答案上添加一些内容,以便更接近我想要的东西吗? - argentum2f
没问题,去做吧。 - LABarnard

2

您可以将显示为不同颜色的行进行着色。

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


# Grid and test function
N = 29;
x,y = np.linspace(-1,1, N*2), np.linspace(-1,1, N)
X,Y = np.meshgrid(x,y)
F = lambda X,Y : np.sin(10*X)/(1+5*(X**2+Y**2))
Z = F(X,Y)


y0 = 10
norm=plt.Normalize(Z.min(), Z.max())
C = plt.cm.Blues_r(norm(Z)/2)
C[y0] = plt.cm.Reds_r(norm(Z[y0])/2)
# 3D Surface plot
plt.figure(figsize = (5,6))

ax = plt.subplot(211, projection='3d')
ax.plot_surface(X,Y,Z, facecolors=C)

# 2D Plot of slice of 3D plot 
plt.subplot(212)
plt.plot(x,Z[y0,:], color=plt.cm.Reds(.7))
plt.show()

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接