首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >matplotlib时间循环(matplotlib.animation?)

matplotlib时间循环(matplotlib.animation?)
EN

Stack Overflow用户
提问于 2016-10-27 21:24:02
回答 1查看 10.7K关注 0票数 0

我正在用matplotlib绘制数据。

我想看一看几秒钟内绘制的数据。

当前脚本(下面)是关闭的。它关闭现有的绘图,并生成一个新的绘图,包括为每个while循环迭代增加一个数据点。

如果"fig=“和"ax1=”语句被输入到循环的上方,我只得到一个空白的图。

代码语言:javascript
复制
import numpy as np
import matplotlib.pyplot as plt 
import numpy as np
import time
#import matplotlib.animation as animation


def animate2(i):

    k=1

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

    while k <=len(i):

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

        ax1.clear
        ax1.plot(i[0:k, 0], i[0:k, 1])

        plt.show()
        time.sleep(1)
        k=k+1

这里是我使用过的一个示例np数组:

代码语言:javascript
复制
test_data=np.array([[3, 7],[1, 2],[8, 11],[5, -12],[20, 25], [-3, 30], [2,2], [17, 17]])

animate2(test_data)

此外,如果您认为matplotlib.animation会更好的工作,请提供一个例子!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-10-27 21:59:38

使用matplot.animation。它使用interval=miliseconds而不是time.sleep()repeat停止循环。frames可以是整数(帧数),也可以是带有数字的列表--列表中的每个元素都作为参数i发送。

代码语言:javascript
复制
import numpy as np
import matplotlib.pyplot as plt 
import matplotlib.animation as animation


def animate2(i):

    ax1.clear()
    ax1.plot(test_data[0:i, 0], test_data[0:i, 1])

# ---

test_data=np.array([[3, 7],[1, 2],[8, 11],[5, -12],[20, 25], [-3, 30], [2,2], [17, 17]])

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

# create animation
animation.FuncAnimation(fig, animate2, frames=range(1, len(test_data)), interval=1000, repeat=False)

# start animation
plt.show()

您还可以使用fargs=tuplet-with-arguments将自己的参数发送到函数。

代码语言:javascript
复制
def animate2(i, data):

    ax1.clear()
    ax1.plot(data[0:i, 0], data[0:i, 1])

# ---

animation.FuncAnimation(fig, animate2, frames=range(1, len(test_data)), 
                         fargs=(test_data, ), interval=1000)

编辑:

我使用这段代码生成动画GIF

(它需要安装imagemagickhttps://stackoverflow.com/a/25143651/1832058)

代码语言:javascript
复制
# create animation
ani = animation.FuncAnimation(fig, animate2, frames=range(1, len(test_data)), interval=1000, repeat=False)

# save animation
ani.save('animation.gif', writer='imagemagick', fps=1)

得到了这个结果

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40294411

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档