python - Matplotlib FuncAnimation 逐步动画函数

标签 python numpy matplotlib animation imshow

我正在尝试使用matplotlibFuncAnimation来制作动画视频。每个帧只是一个 bool n x n 数组,可视化为白色/黑色方 block 。我可以通过提前定义所有数组然后一一检查它们来成功地做到这一点。这使用类似于 matplotlib's example 的代码.

我的项目相当大,我想运行模拟很长时间。因此,我不想创建整个数组列表,然后一一浏览它们。相反,我想定义 animate 函数来执行每个步骤。让我用一个最小的非工作示例来解释。我的实际示例包括更大的数组!

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

def create_video(n):
    global X
    X = np.random.binomial(1, 0.3, size = (n,n))
    
    fig = plt.figure()
    im = plt.imshow(X, cmap = plt.cm.gray)
    
    def animate(t):
        global X
        X = np.roll(X, +1, axis = 0)
        im.set_array(X)
    
    anim = FuncAnimation(
        fig,
        animate,
        frames = 100,
        interval = 1000 / 30,
        blit = True
    )
    
    return anim

anim = create_video(10)

这会初始化一些随机的 10 x 100/1 ,然后只是“滚动”它在每一步。我收到错误。

RuntimeError: The animation function must return a sequence of Artist objects.

如果我删除 return anim,将其替换为 pass,并将 anim = create_video(10) 替换为 create_video( 10),然后我收到警告。

UserWarning: Animation was deleted without rendering anything. This is most likely unintended. To prevent deletion, assign the Animation to a variable that exists for as long as you need the Animation.

显然,我理解得还不够FuncAnimation 。我想要发生的是函数 animate 更新数组 X,通过“滚动”一步,以及执行 im.set_array(X )

最佳答案

this answer 中所述:

As the error suggests, and as can be seen e.g. in the simple_animation example, but also from the FuncAnimation documentation, the init_func as well as the updating func are supposed to return an iterable of artists to animate.

The documentation does not say that this is actually only needed when using blit=True, but since you are using blitting here, it is definitely needed.

所以你有两种方法:

  • 添加

    return im,
    

    动画函数

  • FuncAnimation中设置blit = False

完整代码

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation


def create_video(n):
    global X
    X = np.random.binomial(1, 0.3, size = (n, n))

    fig = plt.figure()
    im = plt.imshow(X, cmap = plt.cm.gray)

    def animate(t):
        global X
        X = np.roll(X, +1, axis = 0)
        im.set_array(X)
        return im, 

    anim = FuncAnimation(
        fig,
        animate,
        frames = 100,
        interval = 1000/30,
        blit = True
    )

    plt.show()

    return anim

anim = create_video(10)

enter image description here

关于python - Matplotlib FuncAnimation 逐步动画函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68956448/

相关文章:

Python-SQLite : Update two record with same identify value

python - 如何在没有相位跳跃的情况下连接正弦波

python - 如何绘制灰色 block ?

python - 像文档一样解析 Sphinx

python - Numpy 重新索引前 N 个自然数

python - Discord.py - 如何检测用户是否提及/ping 机器人

python - 当轮廓部分超出可见区域时删除重复的 matplotlib 轮廓标签

python - numpy 数组 : basic questions

python numpy 掩码意味着性能

python - 在 Mac OSX Mountain Lion 上安装 matplotlib