我正在用matplotlib绘制数据。
我想看一看几秒钟内绘制的数据。
当前脚本(下面)是关闭的。它关闭现有的绘图,并生成一个新的绘图,包括为每个while循环迭代增加一个数据点。
如果"fig=“和"ax1=”语句被输入到循环的上方,我只得到一个空白的图。
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数组:
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会更好的工作,请提供一个例子!
发布于 2016-10-27 21:59:38
使用matplot.animation。它使用interval=miliseconds而不是time.sleep()。repeat停止循环。frames可以是整数(帧数),也可以是带有数字的列表--列表中的每个元素都作为参数i发送。
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将自己的参数发送到函数。
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
(它需要安装imagemagick:https://stackoverflow.com/a/25143651/1832058)
# 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)得到了这个结果

https://stackoverflow.com/questions/40294411
复制相似问题