【问题标题】:Set duration of matplotlib animations when using a generator使用生成器时设置 matplotlib 动画的持续时间
【发布时间】:2014-08-06 17:50:05
【问题描述】:

如何在将 matplotlib 动画保存到文件时指定持续时间? Usually 它将由animation.FuncAnimation()frame 参数给出,但在使用生成器创建动画帧时不会。例如。 using this example

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

def simData():
    t_max = 10.0
    dt = 0.05
    x = 0.0
    t = 0.0
    while t < t_max:
        x = np.sin(np.pi*t)
        t = t + dt
        yield x, t

def simPoints(simData):
    x, t = simData[0], simData[1]
    time_text.set_text(time_template%(t))
    line.set_data(t, x)
    return line, time_text

fig = plt.figure()
ax = fig.add_subplot(111)
line, = ax.plot([], [], 'bo', ms=10)
ax.set_ylim(-1, 1)
ax.set_xlim(0, 10)
time_template = 'Time = %.1f s'    # prints running simulation time
time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)

ani = animation.FuncAnimation(fig, simPoints, simData)
#plt.show()

ani.save('animation.mp4', writer="avconv", codec="libx264")

创建一个 20 秒的视频,显示大约 20 秒。五秒的“模拟时间”,生成器在使用plt.show() 显示时生成的帧的一半。

【问题讨论】:

    标签: python animation matplotlib avconv


    【解决方案1】:

    您在FuncAnimation 上缺少save_count 关键字。如果你传递一个生成器,那么你可以传递要保存的帧数:

    ani = animation.FuncAnimation(fig, simPoints, simData, save_count=200)
    

    迭代似乎一直持续到生成器耗尽或达到save_count。默认值是 100,即使在源代码之外似乎没有很清楚地记录它。

    【讨论】:

    • 感谢您的回答。对我来说,必须指定这一点而不是仅仅耗尽发电机似乎有点荒谬。还是我通过构建自己的生成器来做一些奇怪的事情,该生成器生成一系列元组,告诉动画函数要做什么?
    猜你喜欢
    • 2014-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-20
    • 2012-10-07
    • 2021-03-03
    • 2018-06-15
    • 1970-01-01
    相关资源
    最近更新 更多