python - 如何处理python图中的未知标签和边
问题描述
我有两个数组,a 和 b。我想绘制networkx
图表,将彼此接近的值组合在一起并相应地标记它们。知道怎么做吗?
解决方案
Finding close pairs
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
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]
Output:
>>> 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]]
Plotting a graph
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)
推荐阅读
- angular - Angular gapi 将简单文本上传到 Google Drive
- android - 如何根据android中的屏幕尺寸更改edittext宽度?
- java - Concurrent HashMap 中 Rehashing 期间的检索
- vue.js - VueJS通过代码加载模板组件?
- mongodb - MongoDB - 查找数组长度小于或等于 5 的文档
- android - 在异步任务运行时显示警报框并在任务完成时删除?
- macos - 如何使用 Apple 脚本清除 VLC 播放列表
- ruby-on-rails - form_for 创建属于“比赛”的“项目”为空白
- reactjs - 对 flatList 中的项目进行排序。当我 setState() 时 FlatList 项目不更新
- intellij-idea - 我的第一个编程语言 ANTLR 包 org.antlr.v4.runtime 不存在