
import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.animation import FuncAnimation, PillowWriter# ===== 配置参数 =====k = 5 # 花瓣数量控制:整数→2k瓣,半整数→k瓣frames = 100 # 动画帧数theta_max = 2 * np.pi# ===== 创建图形 =====fig, ax = plt.subplots(subplot_kw={'projection': 'polar'}, figsize=(6, 6))ax.set_title(f'Rose Curve: r = cos({k}θ)', fontsize=14, pad=20)ax.grid(alpha=0.3)line, = ax.plot([], [], 'r-', linewidth=2.5) # 红色曲线# ===== 动画更新函数 =====def animate(frame):theta = np.linspace(0, theta_max * frame / frames, 200)r = np.cos(k * theta) # 核心公式line.set_data(theta, r)return line,# ===== 创建动画 =====anim = FuncAnimation(fig, animate, frames=frames, interval=50, blit=True)# ===== 保存为GIF =====writer = PillowWriter(fps=20) # 20帧/秒,流畅度最佳anim.save('rose_curve.gif', writer=writer, dpi=100)print("saved as 'rose_curve.gif'")plt.tight_layout()plt.show()
Python--数据/图像可视化(雷达图,甘特图,热力图)
细数那些经典教材(编程、数据结构与算法)
Python库巡礼(NumPy,Pandas,SciPy)
推荐文章