zl程序教程

您现在的位置是:首页 >  后端

当前栏目

《Python数据可视化编程实战》——5.4 在matplotlib中创建动画

Python动画matplotlib编程数据 实战 创建 可视化
2023-09-11 14:17:38 时间

本节书摘来自异步社区《Python数据可视化编程实战》一书中的第5章,第5.4节,作者[爱尔兰]Igor Milovanović ,颛青山 译,更多章节内容可以访问云栖社区“异步社区”公众号查看。

5.4 在matplotlib中创建动画

本节将学习如何让图表动起来。有时候,在解释当我们改变变量值时会发生什么情况的时候,动画有着更强的描述性。主要函数库的动画能力有限,但通常已足够了。接下来将解释如何使用它们。

5.4.1 准备工作

从1.1版本开始,一个动画框架被添加到了标准matplotlib库中,该框架主要的类是matplotlib.animation.Animation。这个类是一个基类,它可以针对不同的行为被子类化。实际上,该框架已经提供了几个类:TimedAnimation、ArtistAnimation和FuncAnimation。表5-1给出了这几个类的描述。


screenshot

为了能把动画存储到一个视频文件中,必须安装ffmpeg或者mencoder。这些包的安装根据我们所使用的操作系统的不同以及不同版本间的差别会有所不同,因此我们把它留给亲爱的读者去Google一下有效的相关信息。

5.4.2 操作步骤

下述代码演示了一些matplotlib动画。

import numpy as np

from matplotlib import pyplot as plt

from matplotlib import animation

fig = plt.figure()

ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))

line, = ax.plot([], [], lw=2)

def init():

 """Clears current frame."""

 line.set_data([], [])

 return line,

def animate(i):

 """Draw figure.

 @param i: Frame counter

 @type i: int

 x = np.linspace(0, 2, 1000)

 y = np.sin(2 * np.pi * (x - 0.01 * i)) * np.cos(22 * np.pi * (x - 0.01 * i))

 line.set_data(x, y)

 return line,

# This call puts the work in motion

# connecting init and animate functions and figure we want to draw

animator = animation.FuncAnimation(fig, animate, init_func=init, frames=200, interval=20, blit=True)

# This call creates the video file.

# Temporary, every frame is saved as PNG file

# and later processed by ffmpeg encoder into MPEG4 file

# we can pass various arguments to ffmpeg via extra_args

animator.save(basic_animation.mp4, fps=30,

 extra_args=[-vcodec, libx264],

 writer=ffmpeg_file)

plt.show()

本代码将在执行该文件的文件夹中创建文件basic_animation.mp4,同时显示一个有动画的图形窗口。该视频文件可以用大多数支持MPEG-4格式的视频播放器打开。图形(帧)看上去如图5-4所示。


screenshot


screenshot

5.4.3 工作原理

上面例子中最重要的几个函数是init()、animate()和save()。首先,通过向FuncAnimate{![应为FuncAnimation。]}传入两个回调函数,init和animator。然后,调用它的save()方法保存视频文件。表5-2是关于每一个函数更多的细节内容。


screenshot

5.4.4 补充说明

matplotlib.animation.ArtistAnimation的用法和FuncAnimation不同,我们必须事先绘制出每一个artist,然后用所有artist的不同帧来实例化ArtistAnimation类。Artist动画是对matplotlib.animation.TimedAnimation类的一种封装,每N毫秒绘制一次帧,因此它支持基于时间的动画。

 不幸的是,对于Mac OS X的用户来说,动画框架在该平台上却让人很苦恼,有时候甚至不能工作。这在matplotlib未来的版本中会有所改进。


异步社区 异步社区(www.epubit.com)是人民邮电出版社旗下IT专业图书旗舰社区,也是国内领先的IT专业图书社区,致力于优质学习内容的出版和分享,实现了纸书电子书的同步上架,于2015年8月上线运营。公众号【异步图书】,每日赠送异步新书。