2015-05-26 241 views
3

如何在3d轴中绘制imshow()图像?我试着用这个post。在那篇文章中,曲面图与imshow()图相同,但事实上并非如此。为了说明,这里我把不同的数据:用matplotlib在3d中绘制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) 

这里是我的阴谋:

http://www.physics.iitm.ac.in/~raj/imshow_plot_surface.png

回答

4

我认为在3D VS 2D表面颜色你的错误是由于在表面的颜色数据标准化。如果您将传递至plot_surface facecolor的数据标准化为facecolors=plt.cm.BrBG(data/data.max()),则结果更接近您的预期。

如果你只是想正常的坐标,而不是使用imshow轴,片,你可以使用contourf,这是在3D支持作为matplotlib 1.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 solution更好。

+0

'facecolors = plt.cm.BrBG(data/data.max())'窍门解决了我的问题。 'contourf'给出了相同的情节。 – Raj

+0

填充轮廓'contourf'的好处在于,您可以完全控制“vmin”和“vmax”等颜色限制,您可以显示正确范围的颜色条,并且可以指定平滑度/上面的例子)。映射到表面上的'imshow'是一个好主意,但它是一种黑客,而contourf实际上是在3D中支持的。 –

+0

@Ed Smith使用'contourf',不使用'Z' - 从技术上来说,图像*是* 3D图形,但未能完全控制其位置,这种解决方案并不实用。 – user1735003