之前在使用生成动画时,一直使用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
的多个参数。