我正在尝试使用matplotlib
的FuncAnimation
来制作动画视频。每个帧只是一个 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 10
组 0
/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 theFuncAnimation
documentation, theinit_func
as well as the updatingfunc
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)
关于python - Matplotlib FuncAnimation 逐步动画函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68956448/