There is a simple code to draw lines according some simple rules.
it works but I want to animate it by changing one parameter 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()
I tried to add following code to animate but it doesn't works
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)
CodePudding user response:
You should move all computation and plotting lines within animation
function. The first thing to do in this function is to erase previous plot with ax.cla()
(otherwise new frames will overlap previous ones). I suggest to add ax.set_xlim
and ax.set_ylim
within animation
in order to fix axis limits in each frame and avoid unpleasant axis re-sizing from frame to frame. I also added a title with the current theta_time
value, you can remove it if you want.
Complete Code
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()