python matplotlib画爱心
时间: 2025-08-15 20:57:43 AIGC 浏览: 25 评论: 3
使用 Python 的 `Matplotlib` 库可以绘制出经典的爱心(心形)图形,主要通过参数方程来定义心形的轮廓。以下是详细的实现方法和代码示例。
### 参数方程绘制静态爱心
爱心的数学表达式如下:
- $ x = 16 \cdot \sin^3(t) $
- $ y = 13 \cdot \cos(t) - 5 \cdot \cos(2t) - 2 \cdot \cos(3t) - \cos(4t) $
其中,`t` 是从 `0` 到 `2π` 的参数。
以下是完整的代码实现:
```python
import numpy as np
import matplotlib.pyplot as plt
def draw_heart():
t = np.linspace(0, 2 * np.pi, 1000)
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)
plt.figure(figsize=(6, 6))
plt.plot(x, y, color='red', linewidth=2)
plt.fill(x, y, color='pink') # 填充爱心内部
plt.title("Heart Shape", fontsize=16)
plt.axis('equal') # 保持坐标轴比例一致
plt.axis('off') # 关闭坐标轴
plt.show()
draw_heart()
```
### 带动画效果的跳动爱心
在静态爱心的基础上,可以通过 `matplotlib.animation` 模块实现跳动效果。该方法通过动态调整爱心的缩放比例模拟跳动动画。
```python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
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
fig, ax = plt.subplots(figsize=(6, 6))
t = np.linspace(0, 2 * np.pi, 1000)
def update(frame):
scale = 1 + 0.1 * np.sin(frame) # 动态缩放比例
x, y = heart_shape(t)
x *= scale
y *= scale
ax.clear()
ax.plot(x, y, color='red', linewidth=2)
ax.fill(x, y, color='pink')
ax.set_title("Pulsing Heart", fontsize=16)
ax.axis('equal')
ax.axis('off')
return ax
ani = animation.FuncAnimation(fig, update, frames=np.linspace(0, 2 * np.pi, 120), interval=50, repeat=True)
plt.show()
```
### 心形烟花轨迹(使用 Turtle 模块)
如果希望绘制心形烟花轨迹,可以结合 `turtle` 模块实现,通过点绘制心形路径上的烟花粒子。
```python
import math
import random
import turtle
pen = turtle.Turtle()
pen.speed(0)
pen.color("red")
def heart_shaped_firework(radius, color):
for angle in range(0, 360, 5):
t = math.radians(angle)
x = radius * (16 * math.sin(t) ** 3)
y = radius * (13 * math.cos(t) - 5 * math.cos(2 * t) - 2 * math.cos(3 * t) - math.cos(4 * t))
pen.penup()
pen.goto(x, y)
pen.pendown()
pen.dot(random.randint(10, 20), color)
heart_shaped_firework(10, "orange")
turtle.done()
```
上述方法展示了如何使用 `Matplotlib` 和 `turtle` 等工具绘制静态和动态的爱心图形,适用于数据可视化、艺术设计等场景[^1]。
---
阅读全文
相关推荐



















评论

thebestuzi
2025.06.05
示例涉及Matplotlib和turtle模块,应用广泛。☁️

練心
2025.05.28
结合动画和烟花效果,增加了视觉吸引力。

伯特兰·罗卜
2025.03.16
代码示例详尽,适合初学者学习心形图形绘制。