Tyson
有几种方法可以设置matplotlib绘图的动画。下面让我们看两个使用散点图的最小示例。
(a) 使用交互模式plt.ion()
要制作动画,我们需要一个事件循环。获取事件循环的一种方法是使用plt.ion()(“interactive on”)。然后需要先绘制图形,然后在循环中更新绘图。在循环中,我们需要绘制画布,并为窗口处理其他事件(如鼠标交互等)引入一点暂停。没有这个停顿,窗户就会结冰。最后,我们调用plt.waitforbuttonpress()让窗口保持打开状态,即使动画已经完成。import matplotlib.pyplot as plt
import numpy as np
plt.ion()
fig, ax = plt.subplots()
x, y = [],[]
sc = ax.scatter(x,y)
plt.xlim(0,10)
plt.ylim(0,10)
plt.draw()
for i in range(1000):
x.append(np.random.rand(1)*10)
y.append(np.random.rand(1)*10)
sc.set_offsets(np.c_[x,y])
fig.canvas.draw_idle()
plt.pause(0.1)
plt.waitforbuttonpress()
(b) 使用FuncAnimation
上面的大部分可以使用^{}自动完成。FuncAnimation将处理循环和重绘,并在给定的时间间隔后不断调用函数(在本例中为animate())。动画只会在调用plt.show()时启动,因此会在绘图窗口的事件循环中自动运行。import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np
fig, ax = plt.subplots()
x, y = [],[]
sc = ax.scatter(x,y)
plt.xlim(0,10)
plt.ylim(0,10)
def animate(i):
x.append(np.random.rand(1)*10)
y.append(np.random.rand(1)*10)
sc.set_offsets(np.c_[x,y])
ani = matplotlib.animation.FuncAnimation(fig, animate,
frames=2, interval=100, repeat=True)
plt.show()
赞踩评论- 2020年3月30日 23:25