Matplotlib FuncAnimation用于散点图 [英] Matplotlib FuncAnimation for scatter plot

查看:88
本文介绍了Matplotlib FuncAnimation用于散点图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Matplotlib的FuncAnimation动画每帧动画显示一个点.

I am trying to use the FuncAnimation of Matplotlib to animate the display of one dot per frame of animation.

# 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包正确地为散布图设置动画的任何建议?

Unfortunately, the final animated plot is not the same as original plot. The animated plot also flashes several dots during each frame of animation. Any suggestions on how to correctly animate a scatter plot using the animation package?

推荐答案

示例的唯一问题是如何在animate函数中填充新坐标. set_offsets需要一个Nx2 ndarray,并且您提供了两个1d数组的元组.

The only problem with your example is how you fill the new coordinates in the animate function. set_offsets expects a Nx2 ndarray and you provide a tuple of two 1d arrays.

所以只用这个:

def animate(i):
    data = np.hstack((x[:i,np.newaxis], y[:i, np.newaxis]))
    scat.set_offsets(data)
    return scat,

要保存动画,您可能要调用:

And to save the animation you might want to call:

anim.save('animation.mp4')

这篇关于Matplotlib FuncAnimation用于散点图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆