首页 > 解决方案 > 在 while 循环中定义多行的 Matplotlib 动画

问题描述

我正在尝试绘制 x 和 y 坐标分别由 sk_x(t, tau) 和 sk_y(t, tau) 定义的“n”条线。如果我在循环之外用相同的函数绘制它们,它会很好地绘制函数,但我不能让它们在 animate(i) 函数中工作。一个空的图出现了几分之一秒,然后消失了。问题肯定是我如何处理 animate 函数,但我不能完全弄清楚出了什么问题,它与 tau 作为参数而不是 t 一起工作,但不是相反(参见代码的第二位)。

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


v = 1
k = 1
b = 1
c = 100
f = 200

def sk_y(t, tau):
    y = v*(t-tau)
    return y

def sk_x(t, tau):
    x = v*(np.log((1+k*t)/(1+k*tau)))/k
    return x

fig = plt.figure()
ax = plt.axes(xlim=(0, sk_x(c,0)), ylim=(0, sk_y(c,0)))
lines = [plt.plot([], [])[0] for _ in range(200)]

def init():
    m = 0
    while m < c:
        lines[m].set_data([], [])
        m+=1
    return lines


def animate(i):
    n=-1
    while n<c:
        n+=1
        t = np.linspace(0,i/2-n,100)
        x = sk_x(t+n, n)
        y = sk_y(t+n, n)
        lines[n].set_data(x, y)
    return lines   #edited in 


anim = animation.FuncAnimation(fig, animate, init_func=init, frames=f, interval=20, blit=True)

plt.show()

将此位用于动画功能可以正常工作

def animate(i):
    tau = np.linspace(i*c/f, 0,100)
    x = sk_x(c, tau)
    y = sk_y(c, tau)
    lines[0].set_data(x, y)
    return lines

任何帮助将不胜感激!

编辑:在动画函数中添加了返回函数,但它仍然不能像我想要的那样同时对所有行起作用。

标签: pythonpython-3.xmatplotlib

解决方案


推荐阅读