Matplotlib FuncAnimation 用于散点图

问题描述 投票:0回答:2

我正在尝试使用 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
包正确设置散点图动画有什么建议吗?

python python-3.x matplotlib scatter-plot matplotlib-animation
2个回答
18
投票

您的示例的唯一问题是如何在

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')

6
投票

免责声明,我编写了一个库来尝试使这变得简单,但使用

ArtistAnimation
,称为赛璐珞。您基本上可以像平常一样编写可视化代码,并在绘制每一帧后简单地拍照。这是一个完整的例子:

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')

© www.soinside.com 2019 - 2024. All rights reserved.