Search code examples
python-3.xmatplotlibmplot3d

How to draw simple 3d axis in python3?


enter image description here

I would like to have names of axes as in the figure.


Solution

  • This could be a good starter. Try experiment with it.

    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D
    import numpy as np
    
    fig = plt.figure(figsize=[8,8])
    ax = fig.gca(projection = '3d')
    
    # some settings
    vleng = 4
    aleng = vleng/3.
    
    p = np.array([vleng, 0, 0])
    q = np.array([0, vleng, 0])
    r = np.array([0, 0, vleng])
    
    ax.plot(*np.vstack([[0,0,0], p]).T, color='b')
    ax.plot(*np.vstack([[0,0,0], q]).T, color='g')
    ax.plot(*np.vstack([[0,0,0], r]).T, color='r')
    
    # plotting arrow at terminal of the lines
    ax.quiver(vleng, 0, 0, aleng, 0, 0,  \
              length=0.5, arrow_length_ratio=0.5, color='r')
    ax.quiver(0, vleng, 0, 0, aleng, 0, \
              length=0.5, arrow_length_ratio=0.5, color='m')
    ax.quiver(0, 0, vleng, 0, 0, aleng, \
              length=0.5, arrow_length_ratio=0.5, color='k')
    
    ax.text3D(vleng+1.5, 0, 0, 'X')
    ax.text3D(0, vleng+1.0, 0, 'y')
    ax.text3D(0, 0, vleng+1.0, 'z')
    
    ax.azim = 35    # y rotation (default=270)
    ax.elev = 20    # x rotation (default=0)
    ax.dist = 15    # zoom (define perspective)
    
    ax.set_axis_off( )  # hide all grid
    ax.set_aspect('equal')
    
    # plot poly1
    ax.plot3D( [3.5, 0.25, 2, 3.5], [1, 0.25, 2.5, 1], [1.9, 3.2, 3.8, 1.9], label = 'one line', color='pink' )
    # projection of poly1 on xy-plane
    ax.plot3D( [3.5, 0.25, 2, 3.5], [1, 0.25, 2.5, 1], [0, 0, 0, 0], label = 'one line', color='gray' )
    #ax.legend()
    
    plt.show()
    

    enter image description here