当前位置:   article > 正文

如何使用Python的matplotlib和seaborn库绘制颜色渐变的高级散点图_python散点图渐变色条

python散点图渐变色条

前言

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

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

基本思路

要创建一个更加美观的散点图并且根据距离中心点的远近改变颜色或透明度,可以使用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()

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67

代码解释

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

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

结果

绘制精美散点图效果

延伸阅读

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/181875
推荐阅读
相关标签
  

闽ICP备14008679号