jupyter编辑一个爱心代码
时间: 2025-07-19 09:36:24 浏览: 0
在 Jupyter Notebook 中绘制爱心图形,可以通过 Python 的绘图库实现,例如 `matplotlib` 和 `numpy`。下面将介绍几种不同的方法来绘制静态或动态的爱心图案。
### 使用 Matplotlib 绘制静态爱心图形
可以使用数学公式来定义心形曲线,并利用 `matplotlib` 进行绘制:
```python
import numpy as np
import matplotlib.pyplot as plt
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=(8, 6))
plt.plot(x, y, color='red')
plt.title('Heart Shape')
plt.axis('equal')
plt.axis('off')
plt.show()
```
上述代码中,`x` 和 `y` 是通过心形公式计算出来的点集,最终用 `matplotlib` 绘制成图形[^1]。
### 使用 Turtle 模块绘制爱心
Python 的 `turtle` 模块非常适合初学者学习绘图,也可以用来绘制爱心形状:
```python
import turtle
def draw_heart():
turtle.begin_fill()
turtle.color('red')
turtle.left(140)
turtle.forward(180)
turtle.circle(-90, 200)
turtle.left(120)
turtle.circle(-90, 200)
turtle.forward(180)
turtle.end_fill()
draw_heart()
turtle.done()
```
这段代码定义了一个函数 `draw_heart()`,它使用 `turtle` 命令绘制一个填充红色的爱心[^2]。
### 使用字符打印爱心图案
如果你不需要图形化界面,也可以直接在控制台中使用字符输出爱心:
```python
heart = [
" ** ** ",
"**** ****",
"****** *****",
" ********** ",
" ********* ",
" ******** ",
" ******* ",
" ***** ",
" *** ",
" * "
]
for line in heart:
print(line)
```
此方法适用于简单的文本环境下的爱心显示[^4]。
### 动态爱心曲线
如果希望生成一个动态的爱心动画,可以使用 `matplotlib.animation` 模块:
```python
from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots()
line, = ax.plot([], [], 'r-', lw=2)
def init():
ax.set_xlim(-20, 20)
ax.set_ylim(-20, 20)
return line,
def update(frame):
t = np.linspace(0, frame / 10, 100)
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)
line.set_data(x, y)
return line,
ani = FuncAnimation(fig, update, frames=100, init_func=init, blit=True)
plt.show()
```
该代码创建了一个动态更新的心形曲线,展示了如何使用 `FuncAnimation` 来制作动画效果[^3]。
---
阅读全文
相关推荐


















