FuncAnimationmatplotlib生成动画的常用类,它的工作原理就是不断调用参数func对应的函数生成动画。
FuncAnimation构造方法中关键的三个参数为funcframesfargs

  • func:对于逐帧动画来说就是每一帧的生成方法。
  • frames:暂且不管它在底层如何实现,最终将生成一个可迭代对象,用于每次向func生成的每一帧传递一个值。
  • fargs:除frames之外需要向func传递的参数。

在查找使用FuncAnimation生成动画的资料过程中,发现大多数案例在编写回调函数func时,一般都只构造1个参数,这样fargs参数就用不到了,如果回调函数有多个参数怎么实现呢。

只使用frames参数不使用fargs参数的实现方法(回调函数只有一个参数)

from matplotlib import pyplot as plt
import matplotlib.animation as animation
import numpy as npt = np.linspace(0, 6, 100)
x = 16 * np.sin(t) ** 3
y = 13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(4 * t)
data=[i for i in zip(x,y)]def plot_love(data):x, y = dataplt.scatter(x, y, 60, c="r", alpha=0.7, marker=r"$\heartsuit$")fig=plt.figure(figsize=(5, 3), dpi=100)
plt.axis("off")
animator = animation.FuncAnimation(fig, plot_love, frames=data, interval=80)
animator.save("love.gif", writer='pillow')

在这个案例中:
plot_love就是FuncAnimation构造方法中的func参数,也即回调函数。
frames参数的取值是datadata是一个构造好的二元组-列表,plot_love每次调用从中取一个值。

使用fargs参数的实现方法(回调函数多个参数)

from matplotlib import pyplot as plt
import matplotlib.animation as animation
import numpy as npt = np.linspace(0, 6, 100)
x = 16 * np.sin(t) ** 3
y = 13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(4 * t)def plot_love(num,x,y):plt.scatter(x[:num],y[:num],60, c="r", alpha=0.7, marker=r"$\heartsuit$")fig=plt.figure(figsize=(5, 3), dpi=100)
plt.axis("off")animator = animation.FuncAnimation(fig, plot_love, frames=len(t), fargs=(x,y), interval=80)
animator.save("love0.gif", writer='pillow')

在这个案例中:
plot_love就是FuncAnimation构造方法中的func参数,也即回调函数,这里有3个参数。
frames参数的取值是len(t)len(t)会用于构造成一个长度为len(t)序列,依次将元素传递给回调函数plot_love中的参数num
fargs参数取值为(x,y),在传递给回调函数plot_love时解包为x,y

原理分析

FuncAnimation类的文档中可知,func参数每帧调用一次,第一个参数frameframes参数中的下一个元素,也可以说frames是一个可迭代对象。
因此,在第一个案例中,frames的参数值是一个值序列,每调用一次回调函数就从中取一个值,取值过程不用我们干预。
在第二个案例中,frames的值是一个整数,但是在底层上,会利用range()函数生成一个可迭代对象,作为第一个参数传递给回调函数,机制同第一个案例。fargs作为可变参数传递给回调函数,该参数没有类似frames参数的取值机制,因此,传递过去的值就是对象本身。

func : callableThe function to call at each frame.  The first argument willbe the next value in *frames*.   Any additional positionalarguments can be supplied via the *fargs* parameter.The required signature is::def func(frame, *fargs) -> iterable_of_artists

以下是FuncAnimation类的文档字符串。

def __init__(self, fig, func, frames=None, init_func=None, fargs=None,save_count=None, *, cache_frame_data=True, **kwargs):"""Makes an animation by repeatedly calling a function *func*.Parameters----------fig : `~matplotlib.figure.Figure`The figure object used to get needed events, such as draw or resize.func : callableThe function to call at each frame.  The first argument willbe the next value in *frames*.   Any additional positionalarguments can be supplied via the *fargs* parameter.The required signature is::def func(frame, *fargs) -> iterable_of_artistsIf ``blit == True``, *func* must return an iterable of all artiststhat were modified or created. This information is used by the blittingalgorithm to determine which parts of the figure have to be updated.The return value is unused if ``blit == False`` and may be omitted inthat case.frames : iterable, int, generator function, or None, optionalSource of data to pass *func* and each frame of the animation- If an iterable, then simply use the values provided.  If theiterable has a length, it will override the *save_count* kwarg.- If an integer, then equivalent to passing ``range(frames)``- If a generator function, then must have the signature::def gen_function() -> obj- If *None*, then equivalent to passing ``itertools.count``.In all of these cases, the values in *frames* is simply passed throughto the user-supplied *func* and thus can be of any type.init_func : callable, optionalA function used to draw a clear frame. If not given, the results ofdrawing from the first item in the frames sequence will be used. Thisfunction will be called once before the first frame.The required signature is::def init_func() -> iterable_of_artistsIf ``blit == True``, *init_func* must return an iterable of artiststo be re-drawn. This information is used by the blitting algorithm todetermine which parts of the figure have to be updated.  The returnvalue is unused if ``blit == False`` and may be omitted in that case.fargs : tuple or None, optionalAdditional arguments to pass to each call to *func*.save_count : int, default: 100Fallback for the number of values from *frames* to cache. This isonly used if the number of frames cannot be inferred from *frames*,i.e. when it's an iterator without length or a generator.interval : int, default: 200Delay between frames in milliseconds.repeat_delay : int, default: 0The delay in milliseconds between consecutive animation runs, if*repeat* is True.repeat : bool, default: TrueWhether the animation repeats when the sequence of frames is completed.blit : bool, default: FalseWhether blitting is used to optimize drawing.  Note: when usingblitting, any animated artists will be drawn according to their zorder;however, they will be drawn on top of any previous artists, regardlessof their zorder.cache_frame_data : bool, default: TrueWhether frame data is cached.  Disabling cache might be helpful whenframes contain large objects."""

matplotlib使用FuncAnimation生成动画中func、frames、fargs参数传递思考相关推荐

  1. python动态图表变化_用 Matplotlib 库生成动画图表

    更多文章请关注微信公众号:硬核智能 动画是一种展示现象的有趣方式.相对于静态图表,人类总是容易被动画和交互式图表所吸引.在描述多年来的股票价格.过去十年的气候变化.季节性和趋势等时间序列数据时,动画更 ...

  2. 【Matplotlib】matplotlib.animation.FuncAnimation绘制动态图、交互式绘图汇总(附官方文档)

    文章目录 零.文中用到的相关知识: 一.以sin举例,motplotlib绘制动图 1.绘制sin函数 2.动态画出sin函数曲线 3.点在曲线上运动 4.点,坐标运动 二.单摆例子 1.scipy中 ...

  3. 用python画雨滴_Python使用Matplotlib实现雨点图动画效果的方法

    本文实例讲述了Python使用Matplotlib实现雨点图动画效果的方法.分享给大家供大家参考,具体如下: 关键点 win10安装ffmpeg animation函数使用 update函数 win1 ...

  4. Matplotlib系列(七):动画

    Matplotlib系列目录 文章目录 一. 简介 二. 思维导图 三. Matplotlib动画及图形修改操作 1. 手写代码更新图形实现动画 2. animation模块动画 2.1 Animat ...

  5. Matplotlib 绘制 3D 曲面动画

    Matplotlib 绘制 3D 曲面动画 本文介绍如何使用 Python 中的 Matplotlib 库来绘制动态的 3D 曲面.示例如下: 环境 macOS 11.6 python 3.8 数据 ...

  6. 论文合集 | 李飞飞新论文:深度学习代码搜索综述;Adobe用GAN生成动画(附地址)...

    来源:机器之心 本文约3200字,建议阅读7分钟. 本文介绍了李飞飞新论文,深度学习代码搜索综述,Adobe用GAN生成动画. 本周有李飞飞.朱玉可等的图像因果推理和吴恩达等的 NGBoost 新论文 ...

  7. matplotlib更改networkx生成的图形的背景图。

    我正在尝试使用matplotlib更改networkx生成的图形的背景颜色.但是似乎我的代码仅更改外部背景,而不更改图形本身的背景.示例代码: fig =plt.figure(figsize=(30, ...

  8. python3 xlsxwiter模块插入matplotlib保存到io.BytesIO中的图

    python3 xlsxwiter模块插入matplotlib保存到io.BytesIO中的图 解决问题 代码示例 生成的Excel文件结果 解决问题 1.xlsxwriter生成excel文件的基础 ...

  9. 角色动画中的骨骼蒙皮技术

    参考文献<骨骼皮肤绑定技术的研究及实现> 角色动画中的技术难点:建模技术.运动控制技术.运动捕获.骨骼皮肤绑定技术. 其中,建模技术研究的是角色模型层次及其之间的关系运动:控制技术研究的是 ...

最新文章

  1. Python 多进程、协程异步抓取英雄联盟皮肤并保存在本地
  2. retinaface查看样本
  3. BZOJ 4066: 简单题
  4. select * 和select 所有字段的区别
  5. mysql降序后去重_Mysql 数据记录去重后按字段排序
  6. canvas笔记-文本(fillText)旋转(rotate)
  7. 关于JVM的几道面试题
  8. paip.提升性能---并行多核编程哈的数据结构list,set,map
  9. QT5.12界面再win10下总是莫名卡死
  10. clion生成qt的qrc文件
  11. 微信朋友圈抓取 附近人自动加 附近人朋友圈抓取 最近一直在研究(有兴趣的看网址)...
  12. POC-T批量poc验证工具
  13. IP范围表示法(网络子网划分)
  14. 计算机数据库基础知识填空题,数据库练习题(基础)
  15. 华硕服务器系统都还原不了怎么办,华硕笔记本重装系统后dns解析失败怎么办
  16. idea编辑区左侧行号背景颜色修改
  17. matlab 自定义对象,面向对象: MATLAB 的自定义类 [MATLAB]
  18. 斐波那契数列类 python实现
  19. 贾跃亭要回国圆“造车梦”?FF关联公司广州拿地601亩
  20. VMware一些使用心得

热门文章

  1. ubuntu eclipse java_ubuntu 下安装eclipse amp;java环境配置
  2. Python 解决报错NameError: name ‘LEFT‘ is not defined
  3. 计算机网络自顶向下方法(第六版) 课后题答案 | 第三章
  4. python中的元组介绍
  5. 阿里七年Java练习生,如今年薪50W,P7的大佬是怎么样的?
  6. PHP 命令行模式实战之cli+mysql 模拟队列批量发送邮件(在Linux环境下PHP 异步执行脚本发送事件通知消息实际案例)...
  7. Unity 最新UnityWebRequest下载,同时显示下载进度,和 显示网速,今天贴出来和大家分享
  8. 在计算机中存储器是由内存和外存的区别,简述计算机的内存和外存有何区别与特点?内存是由哪几部分组成?有何特点?...
  9. Linux环境重启系统网卡down,linux重启网卡命令有哪些
  10. 查看全文的css,如何通过纯CSS实现“点击展开全文”功能