在抖音上刷到其他人用 matlab 实现的一个动态心形图,就想也用 Python 实现,摸索了两种实现方式,效果如下:
方法一:
- 利用循环,结合 pyplot 的 pause 与 clf 参数实现图像的动态刷新
import matplotlib.pyplot as plt
import numpy as np# type %matplotlib qt to shown figure in a separate window
x = np.linspace(-1.8, 1.8, 1000)
alpha = 1while alpha <= 21:plt.xlim(-3, 3)plt.ylim(-2, 4)y = abs(x)**(2/3) + 0.9*np.sqrt(3.3 - x**2)*np.sin(alpha*(np.pi)*x)plt.plot(x, y)plt.text(-1.6, 3, r'$f(x)=x^{2/3}+0.9(3.3-x^2)^{1/2}\sin(\alpha\pi x)$') alpha_s = str(round(alpha, 2))tx = plt.text(-0.5, 2.5, r'$\alpha=$' + alpha_s)plt.pause(0.02) # 停顿 0.02 sif alpha <= 20:alpha += 0.1plt.clf() # 清除当前图像else:break
方法二:
- 利用 matplotlib 中的 animation 功能,通过不断更新图像的坐标数值,实现图像的动画效果
- animation 还能生成 gif 动图
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimationdef animate(alpha):x = np.linspace(-1.8,1.8,1000)y = abs(x)**(2/3) + 0.9*np.sqrt(3.3 - x**2)*np.sin(alpha*(np.pi)*x)PLOT.set_data(x, y)time_text.set_text(r'$\alpha$ = ' + str(round(alpha, 2)))return PLOT, time_textfig = plt.figure()
ax = fig.add_subplot(111, xlim=(-2.5, 2.5), ylim=(-2, 4)) # or plt.subplot
PLOT, = ax.plot([], []) # return all the lines
plt.text(-1.2, 3, r'$f(x)=x^{2/3}+0.9(3.3-x^2)^{1/2}\sin(\alpha\pi x)$')
time_text = ax.text(-0.45, 2.5,'') # transform = ax.transAxesani = FuncAnimation(fig, animate, frames = np.arange(1, 20.1, 0.1), interval = 20, repeat = False)
ani.save("heart.gif") # 保存图像为 1 个 gif 文件