Skip to main content
 首页 » 编程设计

python之如何解释散点图中的相同数据点

2024年10月24日20softidea

我正在处理一些具有多个相同数据点的数据。我想在散点图中可视化数据,但散点图不能很好地显示重复项。

如果我更改 alpha 值,则相同的数据点会变得更暗,这很好,但并不理想。

是否有某种方法可以将点的颜色映射到它在数据集中出现的次数?尺寸呢?如何将点的大小分配给它在数据集中出现的次数?

请您参考如下方法:

正如有人指出的那样,这是否有意义在一定程度上取决于您的数据集。如果你有相当离散的点并且精确匹配有意义,你可以这样做:

import numpy as np 
import matplotlib.pyplot as plt 
test_x=[2,3,4,1,2,4,2] 
test_y=[1,2,1,3,1,1,1]   #  I am just generating some test x and y values. Use your data here 
#Generate a list of unique points 
points=list(set(zip(test_x,test_y)))  
#Generate a list of point counts 
count=[len([x for x,y in zip(test_x,test_y) if x==p[0] and y==p[1]]) for p in points] 
#Now for the plotting: 
plot_x=[i[0] for i in points] 
plot_y=[i[1] for i in points] 
count=np.array(count) 
plt.scatter(plot_x,plot_y,c=count,s=100*count**0.5,cmap='Spectral_r') 
plt.colorbar() 
plt.show() 

注意:您需要根据您的点密度调整半径(s 参数中的值 100)。我还使用计数的平方根对其进行缩放,以便点面积与计数成正比。

另请注意:如果点非常密集,使用不同类型的图可能更合适。例如,直方图(我个人喜欢 hexbin 二维数据)在这些情况下是一个不错的选择。