赞
踩
在抖音上刷到其他人用 matlab 实现的一个动态心形图,就想也用 Python 实现,摸索了两种实现方式,效果如下:
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 = 1 while 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 s if alpha <= 20: alpha += 0.1 plt.clf() # 清除当前图像 else: break
import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation def 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_text fig = 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.transAxes ani = FuncAnimation(fig, animate, frames = np.arange(1, 20.1, 0.1), interval = 20, repeat = False) ani.save("heart.gif") # 保存图像为 1 个 gif 文件
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。