赞
踩
我的科研论文中需要绘制一个精美的散点图,表达的是各个散点距离中心点的距离远近情况,特点如下:
要创建一个更加美观的散点图并且根据距离中心点的远近改变颜色或透明度,可以使用matplotlib库的高级功能,并且结合seaborn库来增强图形的美观程度。
下面提供实例,代码作为模板
from cProfile import label from tkinter.ttk import Style import matplotlib.pyplot as plt import numpy as np import seaborn as sns from scipy.spatial.distance import cdist np.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)).T distances = cdist(points, np.array([center])) # 设置颜色或透明度与距离相关 # 这里我们使用距离来设置颜色 colors = distances.flatten() # 开始绘图 sns.set(style="whitegrid") # 使用seaborn的白色网格风格 plt.figure(figsize=(10, 8)) # 设置图的大小 # 绘制散点图,颜色根据距离深浅,大小统一为50 plt.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()
注意:这段代码使用了seaborn.distplot,这个函数在seaborn的最新版本中已经被seaborn.histplot所替代,如果你的seaborn版本较新,应当相应地修改。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。