Plotting imshow () image in 3d in matplotlib
How to build an image imshow()
in 3D axes? I tried with this post. In this post, the surface plot looks the same as imshow()
it does, but it actually isn't. To demonstrate, I took different data here:
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)
Here are my plots:
source to share
I think your error in 2D surface 3D color is due to data normalization in surface colors. If you normalize the data passed to plot_surface
facecolor with facecolors=plt.cm.BrBG(data/data.max())
, the results are closer to what you expected.
If you just want the slice to be normal for the coordinate axis, instead of using imshow
, you could use contourf
which is supported in 3D as of 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()
Although this won't work for a slice at an arbitrary position in 3D, imshow would be better where.
source to share