Python python animation by moving a point drawn across a scatter

I am having trouble making animations in Python. My problem is to animate a 3D point moving along a certain path. I can do this using the animation module and redo the plot at every frame (see the first option in my script). I would like to instead move just the point in each frame without reworking all axes (see the second option in my script). Here's my script:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as an
from mpl_toolkits.mplot3d import Axes3D

# create the parametric curve
t=np.arange(0, 2*np.pi, 2*np.pi/100)
x=np.cos(t)
y=np.sin(t)
z=t/(2.*np.pi)

# create the figure
fig=plt.figure()
ax=fig.gca(projection='3d')

# create the first plot
point=ax.scatter(x[0], y[0], z[0])
line=ax.plot(x, y, z, label='parametric curve')
ax.legend()
ax.set_xlim([-1.5, 1.5])
ax.set_ylim([-1.5, 1.5])
ax.set_zlim([-1.5, 1.5])

# first option - remake the plot at every frame
def update_axes(n, x, y, z, ax):
    ax.cla()
    ax.set_xlim([-1.5, 1.5])
    ax.set_ylim([-1.5, 1.5])
    ax.set_zlim([-1.5, 1.5])
    point=ax.scatter(x[n], y[n], z[n])
    line=ax.plot(x, y, z, label='parametric curve')
    ax.legend()
    return point

ani=an.FuncAnimation(fig, update_axes, 99, fargs=(x, y, z, ax))

# second option - move the point position at every frame
def update_point(n, x, y, z, point):
    point.set_3d_properties(x[n], 'x')
    point.set_3d_properties(y[n], 'y')
    point.set_3d_properties(z[n], 'z')
    return point

#ani=an.FuncAnimation(fig, update_point, 99, fargs=(x, y, z, point))

# make the movie file demo.mp4

writer=an.writers['ffmpeg'](fps=20)
dpi = 100
ani.save('demo.mp4',writer=writer,dpi=dpi)

      

If I choose the second option (comment out the first FuncAnimation and uncomment the second), I get that my point is only moving in the z direction. Any suggestion on what I should do to move it also in the x and y directions?

+3


source to share


1 answer


The reason for only moving along the z-axis is that it set_3d_properties

only applies to the third axis. Therefore, the first two calls set_3d_properties

were unchanged. See working modified code:



from matplotlib import pyplot as plt
import numpy as np
import mpl_toolkits.mplot3d.axes3d as p3
from matplotlib import animation

fig = plt.figure()
ax = p3.Axes3D(fig)

# create the parametric curve
t=np.arange(0, 2*np.pi, 2*np.pi/100)
x=np.cos(t)
y=np.sin(t)
z=t/(2.*np.pi)

# create the first plot
point, = ax.plot([x[0]], [y[0]], [z[0]], 'o')
line, = ax.plot(x, y, z, label='parametric curve')
ax.legend()
ax.set_xlim([-1.5, 1.5])
ax.set_ylim([-1.5, 1.5])
ax.set_zlim([-1.5, 1.5])

# second option - move the point position at every frame
def update_point(n, x, y, z, point):
    point.set_data(np.array([x[n], y[n]]))
    point.set_3d_properties(z[n], 'z')
    return point

ani=animation.FuncAnimation(fig, update_point, 99, fargs=(x, y, z, point))

plt.show()

      

+4


source







All Articles