matplotlib使用底层writer类替代FuncAnimation类逐帧生成动画(优势:更容易理解)

之前在使用生成动画时,一直使用FuncAnimation,总感觉回调函数在传递多个参数时不方便,在查找文档时,发现使用writer类生成动画时,相对于使用FuncAnimation更容易理解。关于writer类参见
https://matplotlib.org/api/animation_api.html#writer-classes

使用FuncAnimation类的实现方法


```python
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')

使用writer类的实现方法

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")

writer = animation.PillowWriter(fps=15)
with writer.saving(fig, "love2.gif"):
    for i in data:
        plot_love(i)
        writer.grab_frame()

两种方法对比

两种方法不同的代码如下:

FuncAnimation类实现

animator = animation.FuncAnimation(fig, plot_love, frames=data, interval=80)
animator.save("love.gif", writer='pillow')

writer类实现

writer = animation.PillowWriter(fps=15)
with writer.saving(fig, "love2.gif"):
    for i in data:
        plot_love(i)
        writer.grab_frame()

帧间时间间隔

使用FuncAnimation类时,使用interval直接定义
使用writer类时,使用fps参数和下面循环的迭代次数来确定。

保存动画方法

使用FuncAnimation类时,使用animation.save方法。
使用writer类时,使用animation.saving上下文管理器配合grab_frame方法。每次循环生成一帧。

使用writer类的优势

虽然很底层、很原始,写起来繁琐,但是更容易理解,只用管好每一帧图像如何生成即可,省得去理解FuncAnimation的多个参数。

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值