[Python] 纯文本查看 复制代码
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
def create_circle_scatter(center_x, center_y, radius, num_points=500):
"""生成圆形散点的坐标"""
angles = np.random.uniform(0, 2 * np.pi, num_points)
radii = np.random.uniform(0, radius, num_points)
x = center_x + radii * np.cos(angles)
y = center_y + radii * np.sin(angles)
return x, y
# 创建画布
fig, ax = plt.subplots(figsize=(8, 10), dpi=150) # 设置dpi为150,提高清晰度
fig.patch.set_facecolor('skyblue')
ax.set_facecolor('skyblue')
# 设置坐标轴范围
ax.set_xlim(-5, 5)
ax.set_ylim(-2, 12)
ax.set_aspect('equal')
ax.axis('off') # 隐藏坐标轴
# 1. 雪人底部(最大的圆)
x_bottom, y_bottom = create_circle_scatter(0, 0, 2, 800)
ax.scatter(x_bottom, y_bottom, c='white', s=20, alpha=0.9, edgecolors='none')
# 2. 雪人中部
x_middle, y_middle = create_circle_scatter(0, 2.8, 1.5, 600)
ax.scatter(x_middle, y_middle, c='white', s=20, alpha=0.9, edgecolors='none')
# 3. 雪人头部
x_head, y_head = create_circle_scatter(0, 4.8, 1, 400)
ax.scatter(x_head, y_head, c='white', s=20, alpha=0.9, edgecolors='none')
# 4. 眼睛
ax.scatter([-0.3, 0.3], [5.1, 5.1], c='black', s=80, marker='o')
# 5. 胡萝卜鼻子
nose_x = np.array([0, 0.1, -0.1])
nose_y = np.array([4.9, 4.7, 4.7])
ax.fill(nose_x, nose_y, color='orange', alpha=0.8)
ax.plot([0, 0], [4.9, 4.7], c='darkorange', linewidth=3)
# 6. 帽子
# 帽檐
hat_brim_x, hat_brim_y = create_circle_scatter(0, 5.9, 0.4, 200)
ax.scatter(hat_brim_x, hat_brim_y, c='black', s=20)
# 帽身
hat_x = np.array([-0.3, 0.3, 0.25, -0.25])
hat_y = np.array([5.9, 5.9, 6.8, 6.8])
ax.fill(hat_x, hat_y, color='black', alpha=0.9)
# 7. 围巾
scarf_x = np.random.uniform(-0.8, 0.8, 300)
scarf_y = np.random.uniform(4.3, 4.6, 300)
ax.scatter(scarf_x, scarf_y, c='red', s=25)
# 围巾飘带
scarf_end_x = np.random.uniform(0.5, 0.9, 100)
scarf_end_y = np.random.uniform(3.8, 4.3, 100)
ax.scatter(scarf_end_x, scarf_end_y, c='red', s=25)
# 8. 纽扣
button_y_positions = [1.5, 2.1, 2.7]
for y_pos in button_y_positions:
ax.scatter(0, y_pos, c='black', s=60, marker='o')
# 9. 手臂(树枝)
# 左臂
left_arm_x = np.random.normal(-1.5, 0.05, 50)
left_arm_y = np.random.normal(3.5, 0.1, 50)
ax.scatter(left_arm_x, left_arm_y, c='brown', s=15)
ax.plot([-2.8, -0.8], [3.8, 3.2], c='brown', linewidth=4)
# 右臂
right_arm_x = np.random.normal(1.5, 0.05, 50)
right_arm_y = np.random.normal(3.5, 0.1, 50)
ax.scatter(right_arm_x, right_arm_y, c='brown', s=15)
ax.plot([2.8, 0.8], [3.8, 3.2], c='brown', linewidth=4)
# 10. 雪花装饰
snow_x = np.random.uniform(-4.5, 4.5, 100)
snow_y = np.random.uniform(-1, 11, 100)
ax.scatter(snow_x, snow_y, c='white', s=10, alpha=0.6, marker='*')
# 添加标题
plt.title('snowman', fontsize=20, color='navy', y=0.95)
plt.tight_layout()
# 保存为PNG文件
plt.savefig('snowman_scatter.png', dpi=300, bbox_inches='tight', facecolor='skyblue')
# 关闭图形以释放内存
plt.close()
print("\n图已成功保存为 'snowman_scatter.png'\n")