mathplotlib没有更新动画



我想对3D散点图中改变位置的点进行动画化。在第一个时间点,散点图中的点具有来自条目scatter[0][1]的坐标,然后在下一个时间点的坐标是scatter[1][2],以此类推。我已经从mathplotlib中设置了动画函数,但是它没有更新。

如果您能帮助解决这个问题,我将不胜感激。

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)

ax.set_xlim3d([0, 100])
ax.set_xlabel('X')
ax.set_ylim3d([0, 100])
ax.set_ylabel('Y')
ax.set_zlim3d([0, 100])
ax.set_zlabel('Z')

scatter=[
np.array([9.956433493781429,
np.array([[50, 50, 50],
[53, 54, 55],
[50, 51, 50],
[52, 52, 52],
[50, 50, 52]])]),
np.array([10.189591392765704,
np.array([[50, 50, 50],
[73, 74, 75],
[70, 71, 70],
[72, 72, 72],
[70, 70, 72]])]),
np.array([10.40490011215984,
np.array([[80, 80, 80],
[83, 84, 75],
[80, 81, 60],
[82, 82, 42],
[88, 80, 52],
[89, 81, 29]])])
]

x=scatter[0][1][:,0]
y=scatter[0][1][:,1]
z=scatter[0][1][:,2]

points, = ax.plot(x, y, z, '*')
txt = fig.suptitle('')
def update_points(num,x, y, z, points):
for i in np.arange(0,len(scatter)):
txt.set_text('time={:f}'.format(scatter[i][0]))
new_x = scatter[i][1][:,0]
new_y = scatter[i][1][:,1]
new_z = scatter[i][1][:,2]
points.set_data(new_x,new_y)
points.set_3d_properties(new_z, 'z')
return points,txt
ani=animation.FuncAnimation(fig, update_points, frames=len(scatter), fargs=(x, y, z, points))
plt.show()

我找到了解决方案。代码需要像这样:


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)

ax.set_xlim3d([0, 100])
ax.set_xlabel('X')
ax.set_ylim3d([0, 100])
ax.set_ylabel('Y')
ax.set_zlim3d([0, 100])
ax.set_zlabel('Z')

scatter=[
np.array([9.956433493781429,
np.array([[50, 50, 50],
[53, 54, 55],
[50, 51, 50],
[52, 52, 52],
[50, 50, 52]])]),
np.array([10.189591392765704,
np.array([[50, 50, 50],
[73, 74, 75],
[70, 71, 70],
[72, 72, 72],
[70, 70, 72]])]),
np.array([10.40490011215984,
np.array([[80, 80, 80],
[83, 84, 75],
[80, 81, 60],
[82, 82, 42],
[88, 80, 52],
[89, 81, 29]])])
]

x=scatter[0][1][:,0]
y=scatter[0][1][:,1]
z=scatter[0][1][:,2]

points, = ax.plot(x, y, z, '*')
txt = fig.suptitle('')
def update_points(num,x, y, z, points):
#for i in range(len(scatter)):
print(num,range(len(scatter)))
txt.set_text('time={:f}'.format(scatter[num][0]))
new_x = scatter[num][1][:,0]
new_y = scatter[num][1][:,1]
new_z = scatter[num][1][:,2]
print(new_x,new_y,new_z)
points.set_data(new_x,new_y)
points.set_3d_properties(new_z, 'z')
return points,txt
ani=animation.FuncAnimation(fig, update_points, frames=3, fargs=(x, y, z, points))
plt.show()