首先,确保已经安装了matplotlib库和numpy库。如果没有安装,可以通过pip来安装:
pip install matplotlib
pip install numpy
了解心形函数公式:
x(t)=
y(t)=13cos(t)−5cos(2t)−2cos(3t)−cos(4t)
定义函数:
def heart_shape(t):
x = 16 * np.sin(t)**3
y = 13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(4 * t)
return x, y
然后,使用以下Python代码来绘制心形线:
import matplotlib.pyplot as plt
import numpy as np
def plot_function_with_process(func, start, end, points=1000):
t = np.linspace(start, end, points)
# 计算爱心形状的坐标
x, y = func(t)
# 创建一个子图
fig, ax = plt.subplots(1, 2, figsize=(12, 4))
# 绘制图像
ax[0].plot(x, y)
ax[0].set_title('Plot of the Function')
ax[0].set_xlabel('X-axis')
ax[0].set_ylabel('Y-axis')
# 绘制绘图过程
for i in range(1, 500):
i*=4
ax[1].clear() # 清除上一步的绘图
ax[1].plot(x[:i], y[:i])
ax[1].set_title('Plotting Process')
ax[1].set_xlabel('X-axis')
ax[1].set_ylabel('Y-axis')
plt.pause(0.001) # 添加延迟以查看绘图过程
# 显示图像
plt.show()
def heart_shape(t):
x = 16 * np.sin(t)**3
y = 13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(4 * t)
return x, y
# 输入函数并绘制图像
plot_function_with_process(heart_shape, 0, 2 * np.pi)
结果展示: