我正在尝试使用 Matplotlib 的 FuncAnimation
来动画显示每帧动画中的一个点。
# modules
#------------------------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as py
from matplotlib import animation
py.close('all') # close all previous plots
# create a random line to plot
#------------------------------------------------------------------------------
x = np.random.rand(40)
y = np.random.rand(40)
py.figure(1)
py.scatter(x, y, s=60)
py.axis([0, 1, 0, 1])
py.show()
# animation of a scatter plot using x, y from above
#------------------------------------------------------------------------------
fig = py.figure(2)
ax = py.axes(xlim=(0, 1), ylim=(0, 1))
scat = ax.scatter([], [], s=60)
def init():
scat.set_offsets([])
return scat,
def animate(i):
scat.set_offsets([x[:i], y[:i]])
return scat,
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=len(x)+1,
interval=200, blit=False, repeat=False)
遗憾的是,最终的动画剧情与原作剧情不尽相同。动画情节还在每一帧动画中闪烁几个点。关于如何使用 animation
包正确动画散点图有什么建议吗?
最佳答案
您的示例的唯一问题是如何在 animate
函数中填充新坐标。 set_offsets
需要一个 Nx2
ndarray 并且您提供了一个包含两个一维数组的元组。
所以只用这个:
def animate(i):
data = np.hstack((x[:i,np.newaxis], y[:i, np.newaxis]))
scat.set_offsets(data)
return scat,
并保存您可能想要调用的动画:
anim.save('animation.mp4')
关于python - 用于散点图的 Matplotlib FuncAnimation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26892392/