概述

FuncAnimationmatplotlib生成逐帧动画的常用类,它的工作原理就是按照一定时间间隔不断调用参数func对应的函数生成动画。

FuncAnimation的继承关系如下:
matplotlib.animation.Animationmatplotlib.animation.TimedAnimationmatplotlib.animation.FuncAnimation

基类matplotlib.animation.Animation定义了三种动画的输出方法。

  • save():通过绘制每帧数据将动画保存为文件。
  • to_html5_video() :将动画转换为HTML5 标签。
  • to_jshtml():以HTML形式生成动画,HTML页面中自带动画控制组件。

六种输出或存储方法

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

fig, ax = plt.subplots()
x = np.arange(0, 2*np.pi, 0.01)
line, = ax.plot(x, np.sin(x))
def animate(i):
    line.set_ydata(np.sin(x + i / 50))
    return line,
ani = animation.FuncAnimation(
    fig, animate, interval=20, blit=True, save_count=50)
# 形式1:利用pillow生成gif文件
ani.save("test.gif",writer='pillow')
# 形式2:输出HTML5 video元素
print(ani.to_html5_video())
# 形式3:将HTML5 video元素保存为html文件
with open("myvideo.html", "w") as f:
    print(ani.to_html5_video(), file=f)
# 形式4:输出html
print(ani.to_jshtml())
# 形式5:以HTML形式在jupyter notebook中显示动画
from IPython.display import HTML
HTML(ani.to_jshtml())
# 形式6:将html保存为文件
with open("myhtml.html", "w") as f:
    print(ani.to_jshtml(), file=f)

原文更详细!!!
原文链接:https://blog.csdn.net/mighty13/article/details/116772125

Logo

一站式 AI 云服务平台

更多推荐