您当前的位置:首页 > IT编程 > python
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:使用numpngw和matplotlib生成png动画的示例代码

51自学网 2021-10-30 23:06:15
  python
这篇教程使用numpngw和matplotlib生成png动画的示例代码写得很实用,希望能帮到您。

在matplotlib官网看到了第三方库numpngw的简介,利用该库作为插件可以辅助matplotlib生成png动画。

numpngw概述

numpngw库可生成PNG静态图像和PNG动画。

  • 通过write_png函数可以将 numpy保存为PNG 文件。
  • 通过 write_apng 函数可以将数组序列保存为 PNG 动画(APNG)文件 。
  • 通过AnimatedPNGWriter类可以将Matplotlib 保存为PNG动画文件。

numpngw库的依赖包是numpy和setuptools。

使用numpngw和matplotlib生成png动画

numpngw+matplotlib实现png动画

import numpy as npfrom matplotlib import pyplot as pltimport matplotlib.animation as animationfrom numpngw import AnimatedPNGWritert = np.linspace(0, 6, 100)x = 16 * np.sin(t) ** 3y = 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 = data  plt.scatter(x, y, 60, c="r", alpha=0.7, marker=r"$/heartsuit$")fig=plt.figure(figsize=(5, 3), dpi=100)plt.axis("off")writer = AnimatedPNGWriter(fps=12)animator = animation.FuncAnimation(fig, plot_love, frames=data)animator.save("love.png", writer=writer)

使用matplotlib和pillow实现gif动画

from matplotlib import pyplot as pltimport matplotlib.animation as animationimport numpy as npt = np.linspace(0, 6, 100)x = 16 * np.sin(t) ** 3y = 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 = data  plt.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')

关键代码解读

# 导入AnimatedPNGWriterfrom numpngw import AnimatedPNGWriter# 初始化AnimatedPNGWriterwriter = AnimatedPNGWriter(fps=12)# 将save函数中的writer参数设为AnimatedPNGWriter实例animator.save("love.png", writer=writer)

通过对比可知,使用 numpngw+matplotlib生成png动画方式非常简单,只用初始化AnimatedPNGWriter,在save函数中指定writer即可。

到此这篇关于使用numpngw和matplotlib生成png动画的示例代码的文章就介绍到这了,更多相关numpngw和matplotlib生成png动画内容请搜索51zixue.net以前的文章或继续浏览下面的相关文章希望大家以后多多支持51zixue.net!


详解如何修改jupyter notebook的默认目录和默认浏览器
selenium+超级鹰实现模拟登录12306
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。