how to set “camera position” for 3d plots using python/matplotlib?

前端 未结 4 2097
情书的邮戳
情书的邮戳 2020-11-28 01:54

I\'m learning how to use mplot3d to produce nice plots of 3d data and I\'m pretty happy so far. What I am trying to do at the moment is a little animation of a rotating surf

4条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-28 02:34

    Minimal example varying azim, dist and elev

    To add some simple sample images to what was explained at: https://stackoverflow.com/a/12905458/895245

    Here is my test program:

    #!/usr/bin/env python3
    
    import sys
    
    import matplotlib.pyplot as plt
    from matplotlib import cm
    from matplotlib.ticker import LinearLocator, FormatStrFormatter
    import numpy as np
    
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    
    if len(sys.argv) > 1:
        azim = int(sys.argv[1])
    else:
        azim = None
    if len(sys.argv) > 2:
        dist = int(sys.argv[2])
    else:
        dist = None
    if len(sys.argv) > 3:
        elev = int(sys.argv[3])
    else:
        elev = None
    
    # Make data.
    X = np.arange(-5, 6, 1)
    Y = np.arange(-5, 6, 1)
    X, Y = np.meshgrid(X, Y)
    Z = X**2
    
    # Plot the surface.
    surf = ax.plot_surface(X, Y, Z, linewidth=0, antialiased=False)
    
    # Labels.
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')
    
    if azim is not None:
        ax.azim = azim
    if dist is not None:
        ax.dist = dist
    if elev is not None:
        ax.elev = elev
    
    print('ax.azim = {}'.format(ax.azim))
    print('ax.dist = {}'.format(ax.dist))
    print('ax.elev = {}'.format(ax.elev))
    
    plt.savefig(
        'main_{}_{}_{}.png'.format(ax.azim, ax.dist, ax.elev),
        format='png',
        bbox_inches='tight'
    )
    
    

    Running it without arguments gives the default values:

    ax.azim = -60
    ax.dist = 10
    ax.elev = 30
    

    main_-60_10_30.png

    Vary azim

    The azimuth is the rotation around the z axis e.g.:

    • 0 means "looking from +x"
    • 90 means "looking from +y"

    main_-60_10_30.png

    main_0_10_30.png

    main_60_10_30.png

    Vary dist

    dist seems to be the distance from the center visible point in data coordinates.

    main_-60_10_30.png

    main_-60_5_30.png

    main_-60_20_-30.png

    Vary elev

    From this we understand that elev is the angle between the eye and the xy plane.

    main_-60_10_60.png

    main_-60_10_30.png

    main_-60_10_0.png

    main_-60_10_-30.png

    Tested on matpotlib==3.2.2.

提交回复
热议问题