pythonnumpymatplotlibmatplotlib-animationtransformation-matrix

Why are matplotlib 3d animations not working when trying to use Line3D objects


I've got this code:

import matplotlib.pyplot as plt 
import mpl_toolkits.mplot3d.axes3d as plt3d
import mpl_toolkits.mplot3d.art3d as artplt3d
import matplotlib.animation as animation

import numpy as np
import math 

def animateBeta():

    def translate(segment_, xTr_, yTr_, zTr_):
        translationMatrix = np.array([
            [1, 0, xTr_],
            [0, 1, yTr_],
            [0, 0, zTr_]
        ])

        return np.matmul(translationMatrix, segment_)

    def rotate(vec_, xRotate_, yRotate_, zRotate_):
        xMat = np.array([
            [1,0,0],
            [0,math.cos(xRotate_), -math.sin(xRotate_)],
            [0, math.sin(xRotate_), math.cos(xRotate_)]
        ])

        yMat = np.array([
            [math.cos(yRotate_), 0, math.sin(yRotate_)],
            [0, 1, 0],
            [-math.sin(yRotate_), 0, math.cos(yRotate_)]
        ])

        zMat = np.array([
            [math.cos(zRotate_), -math.sin(zRotate_), 0],
            [math.sin(zRotate_), math.cos(zRotate_), 0],
            [0, 0, 1]
        ])

        rotationMatrix = np.matmul(zMat, np.matmul(yMat, xMat))

        return np.matmul(rotationMatrix, vec_)

    segment = [
        [0,0],
        [0,0],
        [1, -1]
    ]

    fig = plt.figure()
    ax = plt3d.Axes3D(fig)
    line, = ax.plot(segment[0], segment[1], zs=segment[2], color = 'b')
    artplt3d.line_2d_to_3d(line)

    print(line.__class__)

    def animate(i):
        s0 = [0,0,1]
        s1 = [0,0,-1]
        s1 = translate(rotate(translate(s1, -s0[0], -s0[1], -s0[2]), -i*(math.pi/180),0,-i*(math.pi/180)), s0[0], s0[1], s0[2])
        segment = np.concatenate((np.reshape(s0, (3,-1)),np.reshape(s1, (3,-1))), axis=1)

        #data = ax.plot(segment[0], segment[1], segment[2], color = 'b')
        line.set_3d_properties(zs=segment[2])
        line.set_data_3d(segment[0], segment[1], segment[2])

    anim = animation.FuncAnimation(fig, animate, interval = 1)
    
    plt.show()

animateBeta()

It works when using the commented data = ax.plot(segment[0], segment[1], segment[2], color = 'b') line instead of the following two, (but I'm trying to make it so that I don't have the previous lines drawn when drawing new ones on top).

If you use the code as-is, the animation just seems odd.

I have a theory that line_2d_to_3d isn't working as intended but I'm not sure.


Solution

  • Okay so I was using ax.plot instead of plot3D, and I was under the IMPRESSION that the draw was more correct when using ax.plot