matplotlib 在3D中绘制imshow()图像

juzqafwq  于 2023-05-01  发布在  其他
关注(0)|答案(1)|浏览(222)

如何在3D轴上绘制imshow()图像?我试着用这个post。在那篇文章中,表面图看起来与imshow()图相同,但实际上不是。为了证明这一点,我使用了不同的数据:

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

# create a 21 x 21 vertex mesh
xx, yy = np.meshgrid(np.linspace(0,1,21), np.linspace(0,1,21))

# create vertices for a rotated mesh (3D rotation matrix)
X =  xx 
Y =  yy
Z =  10*np.ones(X.shape)

# create some dummy data (20 x 20) for the image
data = np.cos(xx) * np.cos(xx) + np.sin(yy) * np.sin(yy)

# create the figure
fig = plt.figure()

# show the reference image
ax1 = fig.add_subplot(121)
ax1.imshow(data, cmap=plt.cm.BrBG, interpolation='nearest', origin='lower', extent=[0,1,0,1])

# show the 3D rotated projection
ax2 = fig.add_subplot(122, projection='3d')
ax2.plot_surface(X, Y, Z, rstride=1, cstride=1, facecolors=plt.cm.BrBG(data), shade=False)

以下是我的情节:

hyrbngr7

hyrbngr71#

我认为你在3D和2D表面颜色上的错误是由于表面颜色的数据标准化。如果将传递给plot_surface facecolor的数据标准化为,facecolors=plt.cm.BrBG(data/data.max()),则结果更接近您的预期。
如果你只是想要一个垂直于坐标轴的切片,而不是使用imshow,你可以使用contourf,从matplotlib 1开始,它在3D中得到支持。1.0,

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

# create a 21 x 21 vertex mesh
xx, yy = np.meshgrid(np.linspace(0,1,21), np.linspace(0,1,21))

# create vertices for a rotated mesh (3D rotation matrix)
X =  xx 
Y =  yy
Z =  10*np.ones(X.shape)

# create some dummy data (20 x 20) for the image
data = np.cos(xx) * np.cos(xx) + np.sin(yy) * np.sin(yy)

# create the figure
fig = plt.figure()

# show the reference image
ax1 = fig.add_subplot(121)
ax1.imshow(data, cmap=plt.cm.BrBG, interpolation='nearest', origin='lower', extent=[0,1,0,1])

# show the 3D rotated projection
ax2 = fig.add_subplot(122, projection='3d')
cset = ax2.contourf(X, Y, data, 100, zdir='z', offset=0.5, cmap=cm.BrBG)

ax2.set_zlim((0.,1.))

plt.colorbar(cset)
plt.show()

这段代码会产生如下图像:

尽管这对于3D中任意位置的切片不起作用,但imshow解决方案更好。

相关问题