![](/img/trans.png)
[英]Matplotlib: Coloring scatter plot by density relative to another data set
[英]Matplotlib: Coloring scatter plot based on relative density
我有一个数据集,其中x值包含在数组a中,而相应的y值包含在数组b中。 我正在绘制此数据集的散点图,并使用scipy的gaussian_kde根据点的密度为点着色。 该代码如下所示:
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值)。 我仍然想对FIRST数据集进行散点图绘制,但是这次我想通过FIRST数据集中的点的空间密度与第二个数据集中的点的空间密度之比来进行颜色编码,这样我就可以看到第一个数据集中的对象相对更普遍。 有人对此有什么建议吗?
计算第二个数据集的空间密度。 然后计算两个密度的比率。 按比例排序并像以前一样绘制。
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()
创建一个近似第二个数据集的空间密度的函数。 然后使用该函数在第一个数据集的坐标处估计密度。
from scipy import interpolate
# calculate spatial densities for the two data sets as above
f = interpolate.interp2d(c, d, e, kind='cubic')
r = z / f(x,y)
现在对比率等进行排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.