Python 中关于动画的简单问题

Simple question about animation in Python

有一个简单的代码可以根据一些简单的规则绘制线条。

它可以工作,但我想通过更改一个参数 theta_time.

动画化
import matplotlib.pyplot as plt
import numpy as np
from numpy import *
import matplotlib.animation as animation

List_1 = [6,4,2,1]
List_2 = [0,0,0,0]
List_3 = [6,4,3,2]

fig, ax = plt.subplots()

C_x = 0
C_y = 0
cx = [0]
cy = [0]

theta_time = 1  #I want to update this value from 0 to 10

for freq,amp,phase in zip(List_3,List_1, List_2):

    C_x += amp*np.cos(freq * theta_time + np.deg2rad(phase))
    C_y += amp*np.sin(freq * theta_time + np.deg2rad(phase))
    cx.append(C_x)
    cy.append(C_y)

plt.scatter(cx,cy)
plt.plot(cx, cy, '.r-',linewidth=1)    
plt.show()

我尝试添加以下代码来制作动画,但它不起作用

def animations(theta_time):
    for freq,amp, phase in zip(List_3,List_1, List_2):

    C_x += amp*np.cos(freq * theta_time + np.deg2rad(phase))
    C_y += amp*np.sin(freq * theta_time + np.deg2rad(phase))
    cx.append(C_x)
    cy.append(C_y)

ani = animation.FuncAnimation(
   fig, animations,frames=np.arange(0,1,0.01),interval=10, blit=False)

您应该在 animation 函数内移动所有计算和绘图线。在此函数中要做的第一件事是使用 ax.cla() 擦除之前的图(否则新帧将与之前的帧重叠)。我建议在 animation 中添加 ax.set_xlimax.set_ylim 以固定每个帧中的轴限制并避免帧与帧之间不愉快的轴 re-sizing。我还添加了一个具有当前 theta_time 值的标题,如果需要,您可以将其删除。

完整代码

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation


List_1 = [6,4,2,1]
List_2 = [0,0,0,0]
List_3 = [6,4,3,2]


def animate(theta_time):

    ax.cla()

    C_x = 0
    C_y = 0
    cx = [0]
    cy = [0]

    for freq,amp,phase in zip(List_3,List_1, List_2):

        C_x += amp*np.cos(freq * theta_time + np.deg2rad(phase))
        C_y += amp*np.sin(freq * theta_time + np.deg2rad(phase))
        cx.append(C_x)
        cy.append(C_y)

    ax.scatter(cx,cy)
    ax.plot(cx, cy, '.r-',linewidth=1)

    ax.set_xlim(-15, 15)
    ax.set_ylim(-15, 15)
    ax.set_title(r'$\theta_{time} = $' + str(theta_time))


fig, ax = plt.subplots(figsize = (5, 5))

ani = FuncAnimation(fig = fig, func = animate, interval = 500, frames = 10)

plt.show()