【问题标题】:Simple question about animation in PythonPython中关于动画的简单问题
【发布时间】:2021-11-02 19:11:42
【问题描述】:

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

它可以工作,但我想通过更改一个参数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)

【问题讨论】:

    标签: python numpy matplotlib animation visualization


    【解决方案1】:

    您应该在animation 函数中移动所有计算和绘图线。在此函数中要做的第一件事是用ax.cla() 擦除先前的绘图(否则新帧将与先前的帧重叠)。我建议在animation 中添加ax.set_xlimax.set_ylim,以固定每帧中的轴限制并避免在帧之间重新调整轴的大小。我还添加了一个带有当前 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()
    

    【讨论】:

      猜你喜欢
      • 2018-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-21
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      相关资源
      最近更新 更多