Get data from mplot3d graph

后端 未结 2 582
不知归路
不知归路 2021-01-23 15:19

I can’t find out how to get data from an mplot3d graph. Something similar to the 2D style:

line.get_xdata()

Is it possible?

相关标签:
2条回答
  • 2021-01-23 15:52

    This issue was filed on Github and there is contribution that adds new get_data_3d and set_data_3d methods. Unfortunately, these changes is likely not yet available in distributions. So you might have to continue using private variable line._verts3d.

    See more here: https://github.com/matplotlib/matplotlib/issues/8914

    0 讨论(0)
  • 2021-01-23 15:54

    Line3D

    You can get get the original data from the (private) _verts3d attribute

    xdata, ydata, zdata = line._verts3d
    print(xdata)
    

    Complete example

    import matplotlib as mpl
    from mpl_toolkits.mplot3d import Axes3D
    import numpy as np
    import matplotlib.pyplot as plt
    
    mpl.rcParams['legend.fontsize'] = 10
    
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    
    # Prepare arrays x, y, z
    x = np.arange(5)
    y = np.arange(5)*4
    z = np.arange(5)*100
    
    line, = ax.plot(x, y, z, label='curve')
    
    fig.canvas.draw()
    
    xdata, ydata, zdata = line._verts3d
    print(xdata)  # This prints [0 1 2 3 4]
    
    plt.show()
    

    Some explanation: The problem with get_data or get_xdata is that it will return the projected coordinates once the figure is drawn. So while before drawing the figure, line.get_xdata() would indeed return the correct values, after drawing, it would return something like

    [ -6.14413090e-02  -3.08824862e-02  -3.33066907e-17   3.12113190e-02 6.27567511e-02]
    

    in the above example, which is the x component of the 3D coordinates projected onto 2D.


    There is a pull request to matplotlib, which would allow to get the data via methods get_data_3d. This is still not merged, but might allow the above to be done without using private arguments in a future version of matplotlib.

    Poly3DCollection

    For a plot_surface plot this looks similar, except that the attribute to look at is the ._vec

    surf = ax.plot_surface(X, Y, Z)
    xdata, ydata, zdata, _ = surf._vec
    print(xdata)
    
    0 讨论(0)
提交回复
热议问题