如何使用可变范围

时间:2018-05-02 12:33:40

标签: python python-3.x matplotlib

对于我在for循环的上限范围内写的每个值,我都得到了不同的图。但是我希望通过使用matplotlib动画函数animation.FuncAnimation(),从范围(0,0)设置动画,然后转到(0,15),因为上限会逐渐变化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')

1 个答案:

答案 0 :(得分:2)

matplotlib的动画模块的FuncAnimation函数需要一个图形和一个函数来绘制每个帧,所以首先初始化你的图:

fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)

ax1.set_aspect("equal")
ax1.set_xlim(-30, 30)
ax1.set_ylim(-30, 30)
l1, = ax1.plot([], [], linestyle = "-.", color = "blue")
l2, = ax1.plot([], [], '-.', color = "black")
s1, = ax1.plot([], [], linestyle = None, marker = "o", markersize = 5, color = "blue")
s2, = ax1.plot([], [], linestyle = None, marker = "o", markersize = 5, color = "red")

请注意,不同的线图不包含输入数据,并保存在变量l1,l2,s1和s2中。

现在定义将被调用以绘制每个帧的函数。第一个参数始终是帧编号。此函数应返回使用其方法'set_data'更新的所有绘图对象:

def update_fig(i, x1coor, y1coor, x2coor, y2coor):
    l1.set_data(x1coor[:i+1], y1coor[:i+1])
    l2.set_data(x2coor[:i+1], y2coor[:i+1])
    s1.set_data(x1coor[i], y1coor[i])
    s2.set_data(x2coor[i], y2coor[i])
    return l1, l2, s1, s2,

您现在可以运行动画了(注意'update_fig'参数,除了'i',使用关键字'fargs'传递给函数):

ani = animation.FuncAnimation(fig, update_fig,
                              frames = len(x1coor),
                              fargs = (x1coor, y1coor, x2coor, y2coor),
                              interval = 100,
                              repeat = True,
                              )