【发布时间】:2021-04-08 22:58:31
【问题描述】:
所以,这是我的问题 - 我使用基于 matplotlib 的库,它接受 2D 轴 ax 作为输入,并使用 ax.imshow,假设传递给它的 ax 是 2D 的。我想使用这个库,但要在 3D matplotlib 图上 z=0 的 xy 平面上绘制它的结果。
据我所知:
- Plotting a imshow() image in 3d in matplotlib
- Creating intersecting images in matplotlib with imshow or other function
...我基本上必须使用 ax.plot_surface 才能在 3D 中获得相当于 ax.imshow 的效果。但是,这涉及到重写/修改库,因此所有相应的调用都会被替换。
所以,我试着想出这个简单的例子,看看在 3D 上下文中使用 imshow 可以实现什么:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
fig = plt.figure()
ax3d = fig.add_subplot(projection='3d')
x = np.linspace(0, 1, 100)
y = np.sin(x * 2 * np.pi) / 2 + 0.5
#ax3d.plot(x, y, zs=0, zdir='z', label='curve in (x, y)') # works
# syntax as for 2d plot:
ax3d.plot(x, y, label='curve in (x, y)') # works
# https://matplotlib.org/stable/gallery/images_contours_and_fields/image_demo.html
delta = 0.025
xa = ya = np.arange(0.0, 1.0, delta)
Xa, Ya = np.meshgrid(xa, ya)
Z1a = np.exp(-Xa**2 - Ya**2)
Z2a = np.exp(-(Xa - 1)**2 - (Ya - 1)**2)
Za = (Z1a - Z2a) * 2
# imshow causes NotImplementedError: Axes3D currently only supports the aspect argument 'auto'. You passed in 'equal'.
ax3d.set_aspect('auto') # does not help
im = ax3d.imshow(Za, interpolation='bilinear', cmap=cm.RdYlGn,
origin='lower', extent=[0, 1, 0, 1],
vmax=abs(Za).max(), vmin=-abs(Za).max(),
aspect='auto' # makes imshow pass and draw - but the drawing is not connected to 3d rotation
)
ax3d.set_xlim(0, 1)
ax3d.set_ylim(0, 1)
ax3d.set_zlim(0, 1)
ax3d.view_init(elev=20., azim=-35)
plt.show()
...所以,从句法上讲,它可以被“哄骗”——不幸的是,结果不是 3D 图的“一部分”,因为它不在 z=0 处的 xy 平面上,而且它不会像绘图的其余部分一样随 3D 视图旋转:
所以,我在想 - 有没有办法/某种“hack”,这样我就可以在 3D 图的 z=0 处为 xy 平面“提取”2D Axes matplotlib 对象,然后使用它Axes 对象作为输入传递给库,这将照常进行(但其绘图的最终结果将成为 3D 绘图的一部分)?基本上,就像下面的伪代码:
...
ax2dxy = ax3d.get_2daxes('x', 'y', z=0) # PSEUDO
im = ax2dxy.imshow(Za, interpolation='bilinear', cmap=cm.RdYlGn,
origin='lower', extent=[0, 1, 0, 1],
vmax=abs(Za).max(), vmin=-abs(Za).max(),
)
...
【问题讨论】:
标签: python matplotlib plot