使用不带动画功能的matplotlib进行动画 [英] Animating with matplotlib without animation function

查看:62
本文介绍了使用不带动画功能的matplotlib进行动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以在不使用内置动画功能的情况下对matplotlib中的图形进行动画处理?我发现它们使用起来非常笨拙,并且感觉到只绘制一个点,擦拭图形然后绘制下一个点会更简单.

Is there a way to animate a graph in matplotlib without resorting to the built in animation functions? I find them extremely awkward to use and feel it would be much simpler to just plot a point, wipe the graph, then plot the next point.

我预想诸如此类的东西:

I envision something such as:

def f():
     # do stuff here
     return x, y, t

其中每个t将是不同的帧.

where each t would be a different frame.

我的意思是,我已经尝试过使用plt.clf()plt.close()等之类的方法,但是似乎没有任何效果.

I mean, I've tried stuff like using plt.clf(), plt.close() etc. but nothing seems to work.

推荐答案

在没有FuncAnimation的情况下确定可以进行动画处理.但是,增强功能"的目的并不清楚.在动画中,时间是自变量,即对于每个时间步,您都会生成一些要绘制或类似的新数据.因此,该函数将以t作为输入并返回一些数据.

It is sure possible to animate without FuncAnimation. The purpose of "the enivisioned function", however, is not really clear. In an animation, the time is the independent variable, i.e. for each time step you produce some new data to plot or similar. Therefore the function would take t as an input and give some data back.

import matplotlib.pyplot as plt
import numpy as np

def f(t):
    x=np.random.rand(1)
    y=np.random.rand(1)
    return x,y

fig, ax = plt.subplots()
ax.set_xlim(0,1)
ax.set_ylim(0,1)
for t in range(100):
    x,y = f(t)
    # optionally clear axes and reset limits
    #plt.gca().cla() 
    #ax.set_xlim(0,1)
    #ax.set_ylim(0,1)
    ax.plot(x, y, marker="s")
    ax.set_title(str(t))
    fig.canvas.draw()
    plt.pause(0.1)

plt.show()

此外,不清楚为什么要避免使用FuncAnimation.可以使用FuncAnimation如下制作与上述相同的动画:

Also, it is not clear why you would want to avoid FuncAnimation. The same animation as above can be produced with FuncAnimation as follows:

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

def f(t):
    x=np.random.rand(1)
    y=np.random.rand(1)
    return x,y

fig, ax = plt.subplots()
ax.set_xlim(0,1)
ax.set_ylim(0,1)

def update(t):
    x,y = f(t)
    # optionally clear axes and reset limits
    #plt.gca().cla() 
    #ax.set_xlim(0,1)
    #ax.set_ylim(0,1)
    ax.plot(x, y, marker="s")
    ax.set_title(str(t))

ani = matplotlib.animation.FuncAnimation(fig, update, frames=100)
plt.show()

变化不大,行数相同,在这里看不到任何尴尬.
另外,当动画变得更加复杂,想要重复动画,想要使用blitting或要将其导出到文件中时,您可以从FuncAnimation中获得所有好处.

There is not much changed, you have the same number of lines, nothing really awkward to see here.
Plus you have all the benefits from FuncAnimation when the animation gets more complex, when you want to repeat the animation, when you want to use blitting, or when you want to export it to a file.

这篇关于使用不带动画功能的matplotlib进行动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆