import matplotlib.pyplot as pltimport numpy as np# ========== 1. 全局字体配置,解决中文乱码 ==========plt.rcParams["font.sans-serif"] = ["SimHei"] # 使用黑体渲染中文plt.rcParams["axes.unicode_minus"] = False # 解决负号显示为方块的问题# ========== 2. 生成随机漫步数据(模拟50000步) ==========num_points = 50000x_values = [0]y_values = [0]for _ in range(num_points): x_step = np.random.choice([-1, 1]) * np.random.randint(0, 5) y_step = np.random.choice([-1, 1]) * np.random.randint(0, 5) # 过滤原地踏步的情况 if x_step == 0 and y_step == 0: continue x_values.append(x_values[-1] + x_step) y_values.append(y_values[-1] + y_step)# ========== 3. 绘制高级感散点图 ==========fig, ax = plt.subplots(figsize=(14, 9), dpi=128)# 核心:使用颜色映射(cmap)体现漫步的先后顺序point_numbers = range(len(x_values))ax.scatter(x_values, y_values, c=point_numbers, cmap=plt.cm.Blues, edgecolors='none', s=2, alpha=0.8)# 突出起点与终点ax.scatter(0, 0, c='green', edgecolors='none', s=100, label='起点')ax.scatter(x_values[-1], y_values[-1], c='red', edgecolors='none', s=100, label='终点')# 添加中文标题与图例ax.set_title("随机漫步轨迹模拟 (50,000步)", fontsize=18, pad=20)ax.legend(loc="upper right", fontsize=12)# 隐藏坐标轴,增强纯粹的视觉美感ax.get_xaxis().set_visible(False)ax.get_yaxis().set_visible(False)# ========== 4. 导出高清图表 ==========# 导出高清PNG位图,适合网页展示plt.savefig("random_walk.png", dpi=300, bbox_inches="tight")# 导出矢量PDF,放大不失真,适合专业报表plt.savefig("random_walk.pdf", bbox_inches="tight")plt.close()