用Python在三维空间中实现粒子运动的动画效果

3
我有一个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

'particle_a' 只是一个形状为(N,3)的数组,其中N是时间点数量。
我该如何对其进行动画处理?

1
你尝试过玩弄和扩展matplotlib动画示例吗? - user707650
1个回答

5

通过改编 matplotlib 网站上的此示例 ,您可以用以下代码代表一个在三维空间中移动的粒子:

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()

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接