【问题标题】:Extract plottable Matplotlib 2D axes from 3D plot?从 3D 图中提取可绘制的 Matplotlib 2D 轴?
【发布时间】:2021-04-08 22:58:31
【问题描述】:

所以,这是我的问题 - 我使用基于 matplotlib 的库,它接受 2D 轴 ax 作为输入,并使用 ax.imshow,假设传递给它的 ax 是 2D 的。我想使用这个库,但要在 3D matplotlib 图上 z=0 的 xy 平面上绘制它的结果。

据我所知:

...我基本上必须使用 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


    【解决方案1】:

    这个问题的答案并不完全——而且很可能,从 3D 轴中“提取”“可绘制”2D 轴并不容易——但在下面的示例中,我已经尝试过了,但我无法得到它做很多事情。

    但是,我也尝试在“虚拟”2D 轴上绘制 2D imshow - 并将该数据重新用于 3D 绘图表面 - 它似乎有效:

    import numpy as np
    import matplotlib
    import matplotlib.pyplot as plt
    import matplotlib.cm as cm
    import inspect
    
    fig = plt.figure()
    ax3d = fig.add_subplot(projection='3d')
    #~ ax3d = fig.add_subplot()
    
    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
    
    #print(inspect.getsourcefile(ax3d.plot3D)) # /mingw64/lib/python3.8/site-packages/mpl_toolkits/mplot3d/axes3d.py
    #print(inspect.getsource(ax3d.plot3D)) # def plot! plot3D = plot
    #print(inspect.getsourcefile(matplotlib.axes.Axes)) # /mingw64/lib/python3.8/site-packages/matplotlib/axes/_axes.py
    # imshow in /mingw64/lib/python3.8/site-packages/matplotlib/axes/_axes.py
    print( ax3d.xaxis, ax3d.yaxis , ax3d._position ) # ax3d._position is rect, Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=0.88)
    newax = matplotlib.axes.Axes(fig, (0,0,1,1) )
    print(newax._position) # Bbox(x0=0.0, y0=0.0, x1=1.0, y1=1.0)
    newax.xaxis = ax3d.xaxis
    newax.yaxis = ax3d.yaxis
    
    # 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
    #               )
    imB = newax.imshow(Za, interpolation='bilinear', cmap=cm.RdYlGn,
                   origin='lower', extent=[0, 1, 0, 1],
                   vmax=abs(Za).max(), vmin=-abs(Za).max(),
                   ) # passes, but does not show anything
    #imB.axes = ax3d # ValueError: Can not reset the axes.  You are probably trying to re-use an artist in more than one Axes which is not supported
    #~ print(newax.images) # [<matplotlib.image.AxesImage object at 0x000002505f06f670>]
    #~ print(imB._A) # is there
    fig.canvas.draw() # call to create fig.canvas.renderer
    im, l, b, trans = imB.make_image(fig.canvas.renderer, unsampled=True)
    #print(im)
    ax3d.set_axisbelow(False)
    ax3d.plot_surface(Xa, Ya, np.zeros(Xa.shape), rstride=1, cstride=1, facecolors=np.divide(im, 255.0), shade=False, zorder=-100)
    # ax3d.grid(True, which='major')
    
    ax3d.set_xlim(0, 1)
    ax3d.set_ylim(0, 1)
    ax3d.set_zlim(0, 1)
    ax3d.view_init(elev=20., azim=-35)
    plt.show()
    

    上面的代码产生:

    ...看起来不错...

    现在我只希望我知道如何控制 z 顺序(下方的 plot_surface、网格线和上方的正弦曲线) - 但我为此发布了一个单独的 Q (How to draw Axes3D grid lines over plot_surface() in Matplotlib?)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-02
      • 2011-05-02
      • 2019-05-08
      • 2016-07-07
      • 2012-06-24
      • 2014-05-21
      相关资源
      最近更新 更多