简体   繁体   English

如何将 matplotlib.pause animation 保存到视频中?

[英]How to save a matplotlib.pause animation to video?

I have an animation created with plt.pause as below...我有一个 animation 创建plt.pause如下...

import matplotlib.pyplot as plt

for i in range(10):
    plt.scatter(0, i)
    plt.pause(0.01)

plt.show()

How can I save this as a video file, eg a .mp4 file?如何将其保存为视频文件,例如.mp4文件?

First, I have to redefine the plotting as a function with the plotted point given by a frame i .首先,我必须将绘图重新定义为 function,其绘制点由帧i给出。 plt.pause() can be replaced by matplotlib.animate . plt.pause()可以替换为matplotlib.animate Finally, I used a package suggested here to get the conversion to .mp4 format.最后,我使用了此处建议的 package 来转换为.mp4格式。 You will need to install MoviePy :您将需要安装MoviePy

pip install MoviePy

and then I just animate the function with matplotlib.animate into a .gif format before sending it to MoviePy .然后我只是将 function 与matplotlib.animate动画化为.gif格式,然后再将其发送到MoviePy You'll need to figure out what directory you want this all to happen in. I'm just using the current working directory.您需要弄清楚您希望这一切发生在哪个目录中。我只是使用当前的工作目录。

Here is the code:这是代码:

import matplotlib.pyplot as plt
import matplotlib.animation as ani
import os
import moviepy.editor as mp


frames=20
fig = plt.figure()
ax = plt.gca()
def scatter_ani(i=int):
    plt.scatter(0, i)

name = r"\test.gif"
path = str(os.getcwd())

anim = ani.FuncAnimation(fig, scatter_ani, frames = frames, interval=50)
anim.save(path+name)

clip = mp.VideoFileClip(path+name)
clip.write_videofile(path+r"\test.mp4")

The gif is then然后是gif

结果

To tweak the length of the animation, check out the docs for matplotlib.animate .要调整 animation 的长度,请查看matplotlib.animate文档 For example, if you want to clear all of the previous data-points and show only the dot moving up, then you need to clear the axes in the function, and bound the y-axis so you see the motion ie例如,如果你想清除所有以前的数据点并只显示向上移动的点,那么你需要清除 function 中的轴,并绑定 y 轴以便你看到运动即

def scatter_ani(i=int):
    ax.clear()
    ax.set_ylim(0, frames+1)
    plt.scatter(0, i)

to get:要得到:

结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM