wig*_*ing 6 python numpy matplotlib python-3.x
我试图使用FuncAnimationMatplotlib动画显示每帧动画一个点的显示.
# 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)
Run Code Online (Sandbox Code Playgroud)
不幸的是,最终的动画情节与原始情节不同.在每帧动画期间,动画情节也会闪烁几个点.有关如何使用animation包正确设置散点图动画的建议吗?
hit*_*tzg 11
您的示例的唯一问题是如何填充animate函数中的新坐标.set_offsets期待一个Nx2ndarray,你提供了两个1d数组的元组.
所以只需使用:
def animate(i):
data = np.hstack((x[:i,np.newaxis], y[:i, np.newaxis]))
scat.set_offsets(data)
return scat,
Run Code Online (Sandbox Code Playgroud)
并保存您可能想要调用的动画:
anim.save('animation.mp4')
Run Code Online (Sandbox Code Playgroud)
免责声明,我写了一个库来尝试使这变得简单但使用ArtistAnimation,称为celluloid。您基本上可以像往常一样编写可视化代码,并在绘制每一帧后简单地拍照。这是一个完整的例子:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
from celluloid import Camera
fig = plt.figure()
camera = Camera(fig)
dots = 40
X, Y = np.random.rand(2, dots)
plt.xlim(X.min(), X.max())
plt.ylim(Y.min(), Y.max())
for x, y in zip(X, Y):
plt.scatter(x, y)
camera.snap()
anim = camera.animate(blit=True)
anim.save('dots.gif', writer='imagemagick')
Run Code Online (Sandbox Code Playgroud)