前言

我的科研论文中需要绘制一个精美的散点图,表达的是各个散点距离中心点的距离远近情况,特点如下:

  1. 绘图的美观程度高
  2. 根据距离目标点的距离的不同,各个散点能有颜色或者是透明度上的区分
  3. 相应的统计量是与中心点(目标点)的偏离均值和方差

基本思路

要创建一个更加美观的散点图并且根据距离中心点的远近改变颜色或透明度,可以使用matplotlib库的高级功能,并且结合seaborn库来增强图形的美观程度。

代码

下面提供实例,代码作为模板

from cProfile import labelfrom tkinter.ttk import Styleimport matplotlib.pyplot as pltimport numpy as npimport seaborn as snsfrom scipy.spatial.distance import cdistnp.random.seed(0)# 假设我们已经有了一些数据# 这里生成随机数据来代表散点的坐标x = np.random.rand(100)y = np.random.rand(100)# 假设中心点在(0.5, 0.5)center = np.array([0.5, 0.5])# 计算每个点到中心点的距离points = np.vstack((x, y)).Tdistances = cdist(points, np.array([center]))# 设置颜色或透明度与距离相关# 这里我们使用距离来设置颜色colors = distances.flatten()# 开始绘图sns.set(style="whitegrid")# 使用seaborn的白色网格风格plt.figure(figsize=(10, 8))# 设置图的大小# 绘制散点图,颜色根据距离深浅,大小统一为50plt.scatter(x, y, c=colors, cmap='viridis', alpha=0.6, s=50)# 绘制中心点plt.scatter(center[0], center[1], c='red', s=100, label='Target')# 添加图例plt.legend()# 添加色条plt.colorbar(label='Distance from target')# 设置标题和轴标签plt.title('Scatter Plot by Distance from Target')plt.xlabel('X coordinate ')plt.ylabel('Y coordinate ')# 显示图形plt.show()# 数据分析# 计算统计量,比如均值、标准差等mean_distance = np.mean(distances)std_distance = np.std(distances)# 打印统计结果print(f'Mean distance from center: {mean_distance}')print(f'Standard deviation of distances: {std_distance}')# 可视化距离的分布情况plt.figure(figsize=(8, 6))sns.distplot(distances, bins=20, kde=True)plt.title('Distance Distribution')plt.xlabel('Distance')plt.ylabel('Frequency')plt.show()

代码解释

  1. 首先使用numpy生成了随机的散点数据。
  2. 使用scipy库中的cdist函数计算所有点到中心点的欧氏距离。
  3. 用scatter函数绘制散点图,其中颜色的深浅表示了点距离中心的远近。这里使用viridis色图,它在可视化距离信息时效果不错。
  4. 最后,计算所有距离的均值和标准差,并且使用seaborn的distplot函数绘制距离的分布图,从而对数据进行了基本的统计分析。

注意:这段代码使用了seaborn.distplot,这个函数在seaborn的最新版本中已经被seaborn.histplot所替代,如果你的seaborn版本较新,应当相应地修改。

结果

延伸阅读

如何使用Python和matplotlib绘制机器人运动偏差路径图——实用教程与代码解析