关键词

Matplotlib绘制动图方法详解

本文将详细介绍使用Matplotlib绘制动图的方法。

步骤如下:

导入必要的模块

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

创建画布

fig, ax = plt.subplots()

定义动画函数

def animate(i):
    ax.clear()  # 清空画布
    t = i * dt
    y = A * np.sin(2 * np.pi * f * t)
    ax.plot([0, L], [0, 0], color="black")
    ax.plot([0, L], [y, y], color="red")
    ax.axis([0, L, -1.1 * A, 1.1 * A])
    ax.set_aspect("equal")

设置动画参数

dt = 0.05  # 时间步长,越小精度越高,但速度越慢
T = 2  # 持续时间
frames = int(T / dt)  # 动画帧数
A = 1  # 振幅
f = 1  # 频率
L = 1  # 波长

调用matplotlib.animation.FuncAnimation生成动画对象

ani = FuncAnimation(fig, animate, frames=frames, interval=50, repeat=True)

显示并保存动画

plt.show()
ani.save("test.gif", writer="imagemagick", fps=20)

完整代码如下:

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

fig, ax = plt.subplots()

def animate(i):
    ax.clear()
    t = i * dt
    y = A * np.sin(2 * np.pi * f * t)
    ax.plot([0, L], [0, 0], color="black")
    ax.plot([0, L], [y, y], color="red")
    ax.axis([0, L, -1.1 * A, 1.1 * A])
    ax.set_aspect("equal")

dt = 0.05
T = 2
frames = int(T / dt)
A = 1
f = 1
L = 1

ani = FuncAnimation(fig, animate, frames=frames, interval=50, repeat=True)

plt.show()
# ani.save("test.gif", writer="imagemagick", fps=20)

本文链接:http://task.lmcjl.com/news/4611.html

展开阅读全文