用于散点图的Matplotlib FuncAnimation

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)

  • 我的 `x` 和 `y` 值是一个 Pythonic 的数字列表,因此 `scat.set_offsets(np.c_[x, y])` 对我有用。 (2认同)

Jac*_*vam 5

免责声明,我写了一个库来尝试使这变得简单但使用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)

在此处输入图片说明

  • 当然,请注意,ArtistAnimation 的成本相当高。20 fps 的 2 分钟动画会在内存中创建 2400 个艺术家,与 FuncAnimation 所需的单个艺术家相比,数量相当多。如果您知道其中的含义,那也没关系,但也许新用户会从了解 Func- 和 ArtistAnimation 之间的差异以及如何使用它们中受益更多,而不是使用可能会在以后造成麻烦的黑盒工具。我说的也是关于例如“drawnow”,它的目的是简化事情,但会给几乎任何不理解它的作用的人带来问题。 (2认同)