matplotlib 如何在3D曲面图上高亮显示切片?

ufj5ltwl  于 2023-10-24  发布在  其他
关注(0)|答案(2)|浏览(113)

我有一个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')

enyaitl3

enyaitl31#

您可以使用plot_surface中的facecolor选项以及plot中的类似颜色设置在X或Y方向上对切片进行着色。

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')

**EDIT:**这可以用来突出显示单行(或列,或任意一组点),通过编辑颜色数组来调出特定的单元格,例如:

# 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')

y0u0uwnf

y0u0uwnf2#

您可以对显示为与其他行不同颜色的行进行着色。

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()

相关问题