阅读 324

Python matplotlib 绘制动态图

复习回顾

在matplotlib模块中我们前面学习绘制如折线、柱状、散点、直方图等静态图形。我们都知道在matplotlib模块主要有三层脚本层为用户提供快捷的绘制图形方法,美工层接收到脚本层的命令后将绘制指令发送给后端,后端提供执行绘制操作、事件响应、图形渲染工作。具体的详情可见往期文章如下

  • matplotlib 底层结构:matplotlib模块底层结构

  • matplotlib 绘制折线图:介绍折线图相关属性进行汇总说明

  • matplotlib 绘制柱状图:介绍柱状图相关属性进行汇总说明

  • matplotlib 绘制图形:常见的矩形、圆形等图形绘制方法

  • matplotlib 绘制3D图形:介绍mplot3d绘制3D图形步骤

在matplotlib模块中,除了以上静态图形的绘制,还提供Animation类支持绘制动态图制作

image.png

本期,我们对matplotlib.animation绘制动态图方法学习,Let's go~

1. Animation 概述

Animation 是matplotlib模块制作实时动画的动画类,包含三个子类

  • Animation 是动画类的基类

  • TimedAnimation 是 Animation的子类,可通过绘制时间绘制每一帧动画

  • FuncAnimation 是基于Timed子类,可以通过重复调用fun()方法来绘制动画

  • ArtistAnimation 使用一组Artist对象来绘制动画

image.png

  • 绘制动画特点

    • 绘制对象引用:动画对象要在制作动画时要保持长期有效,否则会被系统资源回收,动画暂停

    • 动画计时器:是对动画对象推进的唯一引用对象

    • 动画保存:需要使用animation.save、animation.To_html5_video或animation.To_jshtml进行动画保存

    • matpoltlib.animation 还提供关于电影格式的类

  • 动画制作方法

    matplotlib.animation.Animation()是动画类的基类,是不能被使用的。常用的两个类主要animation两个子类

    • matplotlib.animation.FuncAnimation

      matplotlib.animation.FuncAnimation(fig, func,  frames=None, init_func=None,  fargs=None,  save_count=None,  * , cache_frame_data=True,  **kwargs) 复制代码

    • matplotlib.animation.ArtistAnimation

      matplotlib.animation.ArtistAnimation(fig,  artists,   *args,   **kwargs) 复制代码

2. 绘制动态图步骤

matplotlib 绘制动态图最重要的是要准备好每一帧显示的数据,通常我们使用FuncAnimation可以传入产生连续数字的func方法,因此绘制动态图主要步骤为:

  • 导入绘制图形的matplotlib.pyplot和制作动态图的matplotlib.animation

import matplotlib.pyplot as plt import matplotlib.animation as animation 复制代码

  • 使用Pyplot.subplots创建一个fig画布对象和一组子图

fig,ax = plt.subplots() 复制代码

  • 调用numpy.random或者numpy.arange()等方法准备x,y轴数据

x = np.arange(0, 2*np.pi, 0.01) 复制代码

  • Axes对象调用plot()、scatter()、hist()等绘制方法,并赋值给list对象

line, = ax.plot(x, np.cos(x),color="pink") 复制代码

  • 需要定义一个专门update data方法生成每一帧显示的数据例如func()

def update(i):     line.set_ydata(np.cos(x + i / 50))     return line, 复制代码

  • 调用animation.FuncAnimation把fig和update()方法

ani = animation.FuncAnimation(     fig, update, interval=20, blit=True, save_count=50) 复制代码

  • 调用plt.show()显示出动态图

plt.show() 复制代码

  • 我们可以调用animation.save("movie.gif",writer="pillow")保存动画为gif格式

ps:我们需要提前pip install pillow 安装pillow库,否则会提示无法使用

 ani.save("movie.gif",writer='pillow') 复制代码

movie.gif

3. 小试牛刀

我们使用animation类绘制直方动态图,在绘制的过程中需要注意几点

  • 使用numpy.linspace生成100个在-5,5的等差数列

  • 使用numpy.random.randn()生成随机数据

  • Axes对象调用hist()返回n,bins,BarContainer

  • 定义一个递归update()函数,使用Python闭包跟踪barcontainer来更新每次直方图矩形高度

  • 调用animation.FuncAnimation()方法绘制动态图

def drawanimationhist():     fig, ax = plt.subplots()     BINS = np.linspace(-5, 5, 100)     data = np.random.randn(1000)     n, _ = np.histogram(data, BINS)     _, _, bar_container = ax.hist(data, BINS, lw=2,                                   ec="b", fc="pink")     def update(bar_container):         def animate(frame_number):             data = np.random.randn(1000)             n, _ = np.histogram(data, BINS)             for count, rect in zip(n, bar_container.patches):                 rect.set_height(count)             return bar_container.patches         return animate     ax.set_ylim(top=55)     ani = animation.FuncAnimation(fig, update(bar_container), 50,                                   repeat=False, blit=True)     plt.show() 复制代码

hist.gif

总结

本期,我们对matplotlib模块制作动态图类animation相关方法学习。在绘制动态图过程中,需要定义func方法来更新每一帧所需要的数据。


作者:盆友圈的小可爱
链接:https://juejin.cn/post/7033006371931226119

文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐