Matplotlib: 相对密度着色散点图

2024-03-28 13:52:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据集,其中x值包含在数组a中,相应的y值包含在数组b中。我正在绘制此数据集的散点图,并使用scipy的高斯分布根据其密度对点进行着色。代码看起来像:

    xy = np.vstack([x,y])
    z = gaussian_kde(xy)(xy)

    # Sort the points by density, so that the densest points are plotted last
    idx = z.argsort()
    x, y, z = x[idx], y[idx], z[idx]

    fig, ax = plt.subplots()
    ax.scatter(x, y, c=z, s=50, edgecolor='')
    plt.show()  

现在,我有另一个数据集(包含在数组c和d中,分别对应于数据集2的x和y值)。我还想绘制第一个数据集的散点图,但这次我想用第一个数据集中的点的空间密度与第二个数据集中的点的空间密度的比率来进行颜色编码,这样我就可以看到第一个数据集中的对象在哪里相对更普遍。有人对如何做这件事有什么建议吗?在


Tags: the数据代码np绘制空间pltscipy
1条回答
网友
1楼 · 发布于 2024-03-28 13:52:12

计算第二个数据集的空间密度。然后计算两种密度的比值。按比率排序,然后像以前一样绘图。在

xy = np.vstack([x,y])
z = gaussian_kde(xy)(xy)

# spacial density of points in second data set
cd = np.vstack([c,d])
e = gaussian_kde(cd)(cd)

# ratio of density in the two data sets
r = z / e

# Sort the points by density ratio, so that the biggest ratios are plotted last
idx = r.argsort()
x, y, r = x[idx], y[idx], r[idx]

fig, ax = plt.subplots()
ax.scatter(x, y, c=r, s=50, edgecolor='')
plt.show()  

编辑:对不起,我错过了一条评论,说这两个数据集的坐标不一致。尝试使用scipy.interpolate.interp2d()创建一个近似于第二个数据集的空间密度的函数。然后使用该函数估计第一个数据集坐标处的密度。在

^{pr2}$

现在对比率等进行排序

相关问题 更多 >