如何处理python图形中的未知标签和边缘 [英] How to deals with unknown label and edges in python graph

查看:72
本文介绍了如何处理python图形中的未知标签和边缘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组,a和b.我想绘制networkx图,将相互靠近的值分组在一起,并相应地标记它们.知道怎么做吗?

I have two arrays, a and b. I would like to draw the networkx graph that group the values together which are close to each other and label them accordingly. Any idea how to do this?

推荐答案

查找紧密对

您的算法找到了ba的每个点的最接近点,但是您需要在距离阈值内确定它们的列表(在大多数情况下可能为空).这可以在scipy.spatial.KDTree协助下实现:

Your algorithm finds closest point of b to each point of a but you need to identify a list of them within some threshold for distance (which might be empty in most of cases). This can be achieved with an assist of scipy.spatial.KDTree:

import numpy as np
from scipy.spatial import KDTree
from itertools import chain
def nearby_pts(a, b, distance):
    # indices of close points of `b` for each point of `a`
    a_data, b_data = np.expand_dims(a, axis=1), np.expand_dims(b, axis=1)
    idx = KDTree(b_data).query_ball_point(a_data, r=distance)
    return idx

然后,您会找到连接从ab的闭合点索引对的边.无法完全矢量化,但我已尽力而为:

Then you can find edges that joins pairs of indices of close points from a to b. This can't be vectorized fully but I made the best I can out of it:

def close_pairs(a, b, distance):
    pts = nearby_pts(a, b, distance).tolist()
    pts_flatten = list(chain(*pts))
    idx = np.repeat(np.arange(len(pts)), [len(n) for n in pts])
    return np.c_[idx, pts_flatten]

输出:

>>> close_pairs(a, b, distance=150)
[[0, 12], [1, 11], [2, 13], [3, 7], [5, 10], [5, 15], [6, 8], [7, 1], [8, 2], [9, 3], [9, 14], [10, 0], [11, 6], [12, 4], [13, 5], [13, 15], [14, 3], [15, 10]]

绘制图形

现在您已经准备好从找到的边缘创建图形,但是首先您需要重新标记节点的第二部分(b),以免与a部分重复.因此,您可以将len(a)添加到b的节点的索引中,就是这样:

Now you're ready to create a graph from edges found but first you need to relabel a second section of nodes (b) not to be duplicated with a section. So you can just add len(a) to indices of nodes of b and that's it:

import igraph as ig

pairs_relabel = close_pairs(a, b, distance=150) + [0, len(a)]
g = ig.Graph(n = len(a) + len(b))
g.add_edges(pairs_relabel)

pal = ig.drawing.colors.ClusterColoringPalette(2) #number of colors used is 2
color = pal.get_many([0]*len(a)+[1]*len(b)) #tags of colors
labels = np.r_[a.astype(int), b.astype(int)] #labels are integral values of nodes

ig.plot(g, bbox=(500, 300), vertex_size=24, 
        vertex_color = color, vertex_label_size=9, vertex_label = labels)

这篇关于如何处理python图形中的未知标签和边缘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆