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的多个参数。

在探索数据可视化时,matplotlib库提供的动画功能是非常有力的工具。特别是结合numpy生成动态数据,可以制作出既美观又信息丰富的动态折线图动画。为了更深入地理解这一过程,我推荐阅读《Python matplotlib 动画绘制实战教程》。该资料详细介绍了如何利用matplotlib绘制动画,尤其适合希望通过实例学习的读者。 参考资源链接:[Python matplotlib 动画绘制实战教程](https://wenku.csdn.net/doc/1za6z54ib6) 首先,要创建一个动态折线图动画,你需要安装matplotlib库(版本1.1.0及以上)和numpy。接下来,我们将通过代码示例步构建动画。首先,导入必要的库: ```python import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation ``` 接着,创建图形和轴,并初始化一个空的折线图对象: ```python fig, ax = plt.subplots() xdata, ydata = [], [] ln, = plt.plot([], [], 'r-', animated=True) ``` 定义一个生成数据的函数,这里使用numpy生成随机数据: ```python def data_gen(): count = 0 while True: yield np.random.rand(10) * (count / 10. + 1) count += 1 ``` 然后,定义更新函数,该函数在每次动画迭代时被调用,用新数据更新折线图: ```python def update(frame): ydata.append(frame[0]) ln.set_data(range(len(ydata)), ydata) return ln, ``` 最后,使用FuncAnimation创建动画: ```python ani = FuncAnimation(fig, update, frames=data_gen, blit=True) plt.show() ``` 这段代码将创建一个动态的折线图动画,每显示由numpy生成的随机数据。`FuncAnimation`函数负责调用`update`函数,`frames`参数设置为`data_gen`函数,它将不断生成新的数据。`blit=True`参数用于优化动画性能,确保只重绘有变化的部分。 通过上述示例,你已经学会了如何使用matplotlibFuncAnimation函数和numpy生成动态数据制作动画。这不仅能增强你的数据可视化技能,还能在讲解数据变化时提供更直观的方式。如果你希望进一步提升你的技能,可以参考《Python matplotlib 动画绘制实战教程》。该教程不仅展示了如何制作动态折线图,还包括了其他动画的制作方法,以及一些高级主题,如动画性能优化和动画保存。 参考资源链接:[Python matplotlib 动画绘制实战教程](https://wenku.csdn.net/doc/1za6z54ib6)
评论 5
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值