2022年4月5日 星期二

[python, 3d, animation] How to update a 3D plot in matplotlib

How to update a 3D plot in matplotlib

井民全, Jing, mqjing@gmail.com


You want to customized your animation in pure clean and update. Here is an example.

Enjoy!
by Jing.


Key

Animate a Line

import matplotlib.pyplot as plt


fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')  # create a 3d grpah and add it to the fig


# Get the line longer and longer

# line: [1,1,1] -> [ i * 10,  i * 10,  i * 10]


for i in range(100):

    x = [1, i * 10]

    y = [1, i * 10]

    z = [1, i * 10]


    ax.clear()  # clean the screen

    ax.plot(x, y, z, label='line')


    plt.show()

    plt.show(block=False)

    plt.pause(0.1)   # update & repair and then wait 0.1 seconds


Code

File: test.py

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D



fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')  # create a 3d grpah and add it to the fig


for i in range(100):

    if i%2 == 0:

        bb = 100

    else:

        bb = -100


    x = [1, bb]

    y = [1, bb]

    z = [1, bb]


    ax.clear()  # clean the screen

    ax.set(xlim=(-500, 500), ylim=(-500, 500), zlim=(-500, 500)) # setup the scale

    ax.set_xlabel('$X$', fontsize=20)                                               # repaint the axis label

    ax.set_ylabel("$Y$ axis label")

    ax.set_zlabel("$Z$ axis label")

    

    ax.plot(x, y, z, label='line')

    ax.legend() # show the legend

    

    plt.show(block=False)

    plt.pause(0.1)   # update & repair and then wait 0.1 seconds



Result