如何使用可变范围设置for循环的动画

2021-10-17 14:58:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到了不同的曲线图,我在循环的上限范围内写的每一个值,正如我所期望的。但是我想通过使用matplotlib动画函数animation.FuncAnimation(),使绘图从范围(0,0)变为(0,15),上限变为1乘1。所以动画总共有16帧。我搞砸了动画部分,所以我粘贴的代码,给出1个情节输出。提前谢谢!你知道吗

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

g = 1.0

def distance(x1,y1,x2,y2):
    r = np.sqrt((x2-x1)**2+(y2-y1)**2)
    return r

def gravit(m1,m2,r):
    f = g*m1*m2/(r**2)
    return f

def angle(y2, y1, x2, x1):
    ydif = y1-y2
    xdif = x1-x2
    angle = np.arctan2(ydif,xdif)
    return angle

m1 = 100
x1, y1 = 0,0
m2 = 1
x2, y2 = -15,-10
vx1 = 1
vy1 = 0
ax1 = 0
ay1 = 0
vx2 = 2
vy2 = 3.9
ax2 = 0
ay2 = 0
x1coor = [x1]
y1coor = [y1]
x2coor = [x2]
y2coor = [y2]


for t in range(0,10):    #This value of 10 should be change from 0 to 15 in the animation
    r = distance(x1,y1,x2,y2)    
    fx1 = gravit(m1, m2, r) * np.cos(angle(y2,y1,x2,x1))
    fy1 = gravit(m1, m2, r) * np.sin(angle(y2,y1,x2,x1))
    ax2 = fx1/m2
    vx2 = vx2 + ax2
    ay2 = fy1/m2
    vy2 = vy2 + ay2
    x2 = x2 + vx2 + 0.5*ax2
    y2 = y2 + vy2 + 0.5*ay2
    x1 = x1 + vx1 + 0.5*ax1
    y1 = y1 + vy1 + 0.5*ay1
    x1coor.append(x1)
    y1coor.append(y1)
    x2coor.append(x2)
    y2coor.append(y2)

plt.axes().set_aspect('equal')
plt.axis([-30,30,-30,30])
plt.plot(x1coor,y1coor, '-.', color='blue')
plt.plot(x2coor,y2coor, '-.', color='black')
plt.scatter(x1,y1,s=m1*20, color='blue')
plt.scatter(x2,y2,s=m2*20, color='red')