使用numpngw和matplotlib生成png动画

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

numpngw概述

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

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

numpngw库的依赖包是numpysetuptools

使用numpngwmatplotlib生成png动画

numpngw+matplotlib实现png动画

import numpy as np
from matplotlib import pyplot as plt
import matplotlib.animation as animation
from numpngw import AnimatedPNGWriter

t = 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 = 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)

使用matplotlibpillow实现gif动画

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

t = 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 = 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')

关键代码解读

# 导入AnimatedPNGWriter
from numpngw import AnimatedPNGWriter

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

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

需要注意的是生成的PNG动画,很多看图软件不能够预览,需要在浏览器中预览。CSDN上传PNG动画有个小BUG,一旦加上水印,就变静态图片了。

在这里插入图片描述

  • 7
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值