import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.animation import FuncAnimation, PillowWriter# ===== 配置参数 =====a, b = 3, 2 # 频率比 (a:b 决定图案复杂度)frames = 100 # 动画帧数duration = 4 # 动画总时长(秒)fps = 25 # 帧率# ===== 生成基础数据 =====t = np.linspace(0, 2 * np.pi, 1000) # 时间参数fig, ax = plt.subplots(figsize=(6, 6))ax.set_xlim(-1.5, 1.5)ax.set_ylim(-1.5, 1.5)ax.set_aspect('equal')ax.grid(True, linestyle='--', alpha=0.4)ax.set_title(f'Lissajous Curve: a={a}, b={b}', fontsize=14, pad=15)# 初始化曲线和相位文本line, = ax.plot([], [], 'b-', lw=2.5, alpha=0.9)phase_text = ax.text(0.05, 0.95, '', transform=ax.transAxes, fontsize=12, color='darkred', weight='bold')# ===== 动画更新函数 =====def animate(frame): # 相位差从0 → 2π 循环变化 delta = 2 * np.pi * frame / frames # 计算李萨如坐标 x = np.sin(a * t + delta) y = np.sin(b * t) # 更新曲线和文本 line.set_data(x, y) phase_text.set_text(f'Phase shift: δ = {delta:.2f} rad\n({delta / np.pi:.2f}π)') return line, phase_text# ===== 创建动画 =====ani = FuncAnimation( fig, animate, frames=frames, interval=1000 / fps, # 每帧间隔(毫秒) blit=True, repeat=True)# ===== 保存为GIF =====print("正在生成GIF动画 ..")writer = PillowWriter(fps=fps)# 显示动画(可选)plt.tight_layout()plt.show()