在 Python 中为 3D 中的粒子运动设置动画

Tom*_*Tom 3 python animation matplotlib

对于一个粒子,我有 3xN 阵列位置随时间变化。我想获取每个时间点的坐标,将该位置绘制为 3D 轴上的一个点,然后重复,创建动画。

我可以使用 matplotlib 的 Axes3D 创建此效果的单个图像

x_a = particle_a[:,0]
y_a = particle_a[:,1]
z_a = particle_a[:,2]

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')


ax.scatter(x_a, y_a, z_a, c='b')
plt.show
Run Code Online (Sandbox Code Playgroud)

'particle_a' 只是一个形状为 (N,3) 的数组,其中 N 是时间点的数量。

我怎样才能动画这个?

xnx*_*xnx 5

改编来自 matplotlib 站点的此示例,您可以使用以下命令表示在 3D 中移动的粒子:

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

def make_helix(n):
    theta_max = 8 * np.pi
    theta = np.linspace(0, theta_max, n)
    x, y, z = theta, np.sin(theta), np.cos(theta)
    helix = np.vstack((x, y, z))

    return helix

def update_lines(num, dataLines, lines) :
    for line, data in zip(lines, dataLines) :
        line.set_data(data[0:2, num-1:num])
        line.set_3d_properties(data[2,num-1:num])
    return lines

# Attach 3D axis to the figure
fig = plt.figure()
ax = p3.Axes3D(fig)

n = 100
data = [make_helix(n)]

lines = [ax.plot(data[0][0,0:1], data[0][1,0:1], data[0][2,0:1], 'o')[0]]

# Setthe axes properties
ax.set_xlim3d([0.0, 8*np.pi])
ax.set_xlabel('X')

ax.set_ylim3d([-1.0, 1.0])
ax.set_ylabel('Y')

ax.set_zlim3d([-1.0, 1.0])
ax.set_zlabel('Z')

ax.set_title('3D Test')

# Creating the Animation object
ani = animation.FuncAnimation(fig, update_lines, n, fargs=(data, lines),
                              interval=50, blit=False)
plt.show()
Run Code Online (Sandbox Code Playgroud)

(替换helix为您自己的数据并相应地设置轴限制)。