在 Matplotlib 中使用 D3.js 动画创建动画 GIF 文件
matplotlibpythondata visualization更新于 2025/9/12 7:40:17
要使用 D3.js 动画创建动画 GIF 文件,我们可以采取以下步骤 −
- 设置图形大小并调整子图之间和周围的填充。
- 创建新图形或激活现有图形。
- 向当前图形添加轴并使其成为当前轴。
- 使用空列表绘制一条线。
- 要初始化线条,请传递空列表。
- 要为正弦曲线制作动画,请更新正弦曲线值并返回线条实例。
- 使用 PillowWriter() 类获取电影编写器实例。
- 使用保存 .gif 文件PillowWriter。
示例
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)
def init():
line.set_data([], [])
return line,
def animate(i):
x = np.linspace(0, 2, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i))
line.set_data(x, y)
return line,
ani = animation.FuncAnimation(fig, animate, init_func=init, frames=200, interval=20, blit=True)
writer = animation.PillowWriter(fps=25)
ani.save("sine.gif", writer=writer)
输出


相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

