您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Matplotlib创建实时动画图

Matplotlib创建实时动画图

这将从输出文件中的数据制作出不错的动画:

from matplotlib import pyplot as plt
from matplotlib import animation


fig = plt.figure()

with open('error_output.txt') as fobj:
    x, y = zip(*([float(x) for x in line.split(',')] for line in fobj))


def animate(n):
    line, = plt.plot(x[:n], y[:n], color='g')
    return line,

anim = animation.FuncAnimation(fig, animate, frames=len(x), interval=1000)
plt.show()

这里是一个允许通过以下方式实时生成数据动画的版本regr_magic

import random
import time

from matplotlib import pyplot as plt
from matplotlib import animation


class RegrMagic(object):
    """Mock for function Regr_magic()
    """
    def __init__(self):
        self.x = 0
    def __call__(self):
        time.sleep(random.random())
        self.x += 1
        return self.x, random.random()

regr_magic = RegrMagic()

def frames():
    while True:
        yield regr_magic()

fig = plt.figure()

x = []
y = []
def animate(args):
    x.append(args[0])
    y.append(args[1])
    return plt.plot(x, y, color='g')


anim = animation.FuncAnimation(fig, animate, frames=frames, interval=1000)
plt.show()

全班RegrMagic都是模拟的帮助者Regr_magic()。该__call__方法使此类的实例的行为类似于函数。它有状态,并产生数字1, 0.565652, 0.65566等等。对于每个呼叫(第二个数字是任意的数)。它还具有时间延迟以模仿计算时间。

重要的是frames()。替换Regr_magic()Regr_magic(),应该很好。

没有模拟的版本:

import random
import time

from matplotlib import pyplot as plt
from matplotlib import animation


def frames():
    while True:
        yield Regr_magic()


fig = plt.figure()

x = []
y = []
def animate(args):
    x.append(args[0])
    y.append(args[1])
    return plt.plot(x, y, color='g')


anim = animation.FuncAnimation(fig, animate, frames=frames, interval=1000)
plt.show()
其他 2022/1/1 18:44:33 有471人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶