matplotlib 如何制作由三个函数x=()、y=()、z=()定义的3D图的动画?

5ssjco0h  于 2022-11-15  发布在  其他
关注(0)|答案(1)|浏览(138)
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import mpl_toolkits.mplot3d as Axes3D

r = 20
h = 1.7
phi = np.linspace(0, 4*np.pi, 1000)
theta = np.linspace(-np.pi/4, np.pi/4, 1000)
#theta = np.arcsin(0.524)
x = r * np.cos(phi)
y = r * np.sin(phi) * np.cos(theta) - h * np.sin(theta)
z = r * np.sin(phi) * np.sin(theta) + h * np.cos(theta)

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

ax.plot(x, y, z, '-r', linewidth = 3)

ax.set_xlabel('X', fontweight = 'bold', fontsize = 14)
ax.set_ylabel('Y', fontweight = 'bold', fontsize = 14)
ax.set_zlabel('Z', fontweight = 'bold', fontsize = 14)

plt.title('Parametric pancake', fontweight = 'bold', fontsize = 16)

plt.show()

这段代码绘制了由x,y和z方程定义的曲线。这很好,但我需要绘制它,即有一个点在移动时绘制曲线,而没有曲线,这已经绘制好了。我该如何实现这一点?此外,我需要曲线周期性地移动-Angular phi继续旋转,Angular theta从-90度谐移到+90度有点像钟摆,最后一件事是,我如何使点在一个循环中移动,这样当绘制曲线时,它就不会停止,而是继续沿着曲线移动?

wfsdck30

wfsdck301#

您需要创建一个animate回调来更新数据。

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

r = 20
h = 1.7
N=1000
phi = np.linspace(0, 4*np.pi, N)
theta = np.linspace(-np.pi/4, np.pi/4, N)
#theta = np.arcsin(0.524)
x = r * np.cos(phi)
y = r * np.sin(phi) * np.cos(theta) - h * np.sin(theta)
z = r * np.sin(phi) * np.sin(theta) + h * np.cos(theta)

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

ax.set_xlim(x.min(),x.max())
ax.set_ylim(y.min(),y.max())
ax.set_zlim(z.min(),z.max())

pltdata, = ax.plot(x[:1], y[:1], z[:1], '-r', linewidth = 3)
lastPoint, = ax.plot(x[0], y[0], z[0], 'b', marker='o')
txt = ax.text(x[0], y[0], z[0]+0.5, 'i=0')

ax.set_xlabel('X', fontweight = 'bold', fontsize = 14)
ax.set_ylabel('Y', fontweight = 'bold', fontsize = 14)
ax.set_zlabel('Z', fontweight = 'bold', fontsize = 14)

plt.title('Parametric pancake', fontweight = 'bold', fontsize = 16)

def animate(i):
    pltdata.set_data(x[:i+1], y[:i+1])
    pltdata.set_3d_properties(z[:i+1])
    lastPoint.set_data(x[i:i+1], y[i:i+1])
    lastPoint.set_3d_properties(z[i:i+1])
    txt.set_text(f"{i=}")
    txt.set_x(x[i])
    txt.set_y(y[i])
    txt.set_z(z[i]+0.5)
    return [pltdata, lastPoint, txt]

theAnim = animation.FuncAnimation(fig, animate, frames=N, interval=100, blit=True, repeat=False)
plt.show()
#theAnim.save('out.gif')

相关问题