Jupyter Notebook圣诞树代码
时间: 2025-05-21 21:39:14 浏览: 16
### Jupyter Notebook 中绘制圣诞树
以下是使用 `matplotlib` 库在 Jupyter Notebook 中绘制圣诞树的一个示例代码:
```python
import matplotlib.pyplot as plt
import numpy as np
# 设置画布大小
plt.figure(figsize=(4, 8))
# 定义三角形部分(树冠)
def draw_triangle(x, y, width, height):
x_coords = [x - width / 2, x, x + width / 2]
y_coords = [y, y + height, y]
plt.fill_between(x_coords, y_coords, color='green')
# 绘制树干
def draw_trunk(x, y, width, height):
rectangle = plt.Rectangle((x - width / 2, y), width=width, height=height, color='brown')
plt.gca().add_patch(rectangle)
# 主体函数
def draw_christmas_tree():
base_x = 0
base_y = 0
# 绘制三个层次的树冠
draw_triangle(base_x, base_y + 6, 6, 3) # 上层
draw_triangle(base_x, base_y + 3, 8, 3) # 中层
draw_triangle(base_x, base_y, 10, 3) # 下层
# 绘制树干
draw_trunk(base_x, base_y - 2, 2, 4)
# 添加装饰物(星星)
star_x = base_x
star_y = base_y + 9
plt.plot(star_x, star_y, marker='*', markersize=20, color='yellow')
# 配置绘图参数
plt.axis('equal') # 确保比例一致
plt.axis('off') # 关闭坐标轴
plt.show()
draw_christmas_tree()
```
此代码通过定义两个辅助函数分别绘制树冠和树干,并利用 `matplotlib` 的绘图功能完成整个圣诞树的设计。
如果希望进一步增强视觉效果,可以引入其他库如 `pygraphviz` 或者 `networkx` 来实现更复杂的图形布局[^2]。然而对于简单的圣诞树图案而言,上述方法已经足够满足需求。
阅读全文
相关推荐

















