python - 用于散点图的 Matplotlib FuncAnimation

标签 python python-3.x numpy matplotlib

我正在尝试使用 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/

相关文章:

Python - 根据条件读取文本文件中的特定行

Python:如何将变量保存在内存中,以便可以从其他 Python 脚本中调用它?

python - 无法使用 python rasterio、gdal 打开 jp2 (来自哨兵)

python - python写的一个正在运行的服务器进程如何查找绑定(bind)地址和端口?

python - 正则表达式仅从随机文本中搜索网站名称

python - 对 numpy 数组中的每一行应用函数?

javascript - 使用 selenium 和 python 在网页中打印 javascript 的输出

python - python 列表的子集基于同一列表的元素组,pythonically

python - numpy数组用于范围内的浮点值

python - 如何创建一个 numpy 数组,该数组对应于一个点是否位于 numpy 多边形数组内?