Python matplotlib动画保存的帧与预期帧不同

Python matplotlib动画保存的帧与预期帧不同,python,matplotlib,Python,Matplotlib,matplotlib animation.save未提供正确的帧和迭代 当我使用%matplotlib笔记本后端在Jupyter中运行代码时,我的绘图运行良好,并在所需的结束帧(n=100)上结束。但当我播放保存的mp4时,我以n=99结束 我更改了frames=130,笔记本后端再次在n=100时完美结束,这意味着a.event\u source.stop()被正确调用。但是当我回顾mp4时,它以n=129结束 import matplotlib.animation as animation

matplotlib animation.save未提供正确的帧和迭代

当我使用
%matplotlib笔记本
后端在Jupyter中运行代码时,我的绘图运行良好,并在所需的结束帧(n=100)上结束。但当我播放保存的mp4时,我以n=99结束

我更改了
frames=130
,笔记本后端再次在n=100时完美结束,这意味着a.event\u source.stop()被正确调用。但是当我回顾mp4时,它以n=129结束

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

n = 100
x = np.random.randn(n)

# create the function that will do the plotting, where curr is the current frame
def update(curr):
    # check if animation is at the last frame, and if so, stop the animation a
    if curr == n:
        a.event_source.stop()
    plt.cla()
    bins = np.arange(-4, 4, 0.5)
    plt.hist(x[:curr], bins=bins)
    plt.axis([-4,4,0,30])
    plt.gca().set_title('Sampling the Normal Distribution')
    plt.gca().set_ylabel('Frequency')
    plt.gca().set_xlabel('Value')
    plt.annotate('n = {}'.format(curr), [3,27])

fig = plt.figure()
a = animation.FuncAnimation(fig, update, interval=10, frames=None)
a.save('norm_dist.mp4')
查看,如果
frames
设置为none,它将使用
itertools.count(interval)
作为要使用的帧数。你看到99而不是100的原因是因为它是零索引的

您可以使用
frames=n
设置所需的帧数,并使用以下各项测试其正确性:

ffprobe -v error -select_streams v:0 -show_entries stream=nb_frames -of default=nokey=1:noprint_wrappers=1 norm_dist.mp4

所以这并不是真的,而是为了子孙后代:


看起来
a.event\u source.stop()
正在使函数短路。尝试将支票移到末尾,看看是否能得到预期的帧数。

谢谢您的建议。是的,我试过了,但它并没有改变任何结果。当frames设置为130时,额外的帧仍然会出现,当我将frames设置为none时,它仍然不会在100处停止。我终于了解了您和重要的fBeingearnest的反馈发生了什么。简而言之,完成了100帧。我的动画恰好完成了我想要的100个片段。但是我被显示不显示n=100的屏幕甩了,因为代码要求它停在99。我应该对注释做+1来解释零索引。谢谢。
curr==n
所在的帧未保存,因为您已停止动画。但它仍然显示,因为您的代码仍在继续。您可以在
a.event\u source.stop()
之后直接放置一个
return
,以使函数在结束之前不继续执行。在
a.event\u source.stop()之后添加返回不会改变结果。更新绘图后也没有将停止放置到。在
a.event\u source.stop()之后添加
return
,对我来说很有效-在屏幕上的最后一帧和保存的文件中得到n=99。在情节更新后停下来也无济于事。我终于明白了你和tsnowlan的反馈到底是怎么回事。简而言之,完成了100帧。我的动画恰好完成了我想要的100个片段。但是我被显示不显示n=100的屏幕甩了,因为代码要求它停在99。我应该对注释做+1来解释零索引。谢谢