如何提取并绘制networkx图中的直接邻居及其邻居?
考虑下面这个例子
import networkx as nx
G = nx.Graph()
G.add_edges_from(
[('A', 'B'), ('A', 'C'), ('D', 'B'), ('E', 'C'),
('H', 'C'), ('Y', 'I')])
nx.draw_networkx(G)
我想提取并绘制包含'A'及其所有邻居的子图,然后再提取邻居的邻居,依此类推,进行
我在使用
zn = G.subgraph(nx.all_neighbors(G, 'A'))
nx.draw_networkx(zn)
这里可以做些什么呢?谢谢!
3 个回答
1
也许用递归的方法能帮到你。
zm = nx.Graph()
start = 'D'
def node_search(start,i):
y = 0
while y < i:
zn = G.subgraph(nx.all_neighbors(G, start))
for node in zn:
zm.add_edge(node, start)
if zn.has_node(node):
node_search(node,y)
y = y + 1
node_search(start,2)
zm.edges()
从'D'开始,走2步,我得到的结果是: EdgeView([('B', 'D'), ('B', 'A')])
2
一个选择是构建一个 accumulate
/ union
,把所有的 descendants_at_distance
合在一起:
des_atd = [
des
for i in range(len(G))
if (des := nx.descendants_at_distance(G, "A", distance=i))
]
from itertools import accumulate
out = list(accumulate(des_atd, set.union))
# [{'A'}, {'A', 'B', 'C'}, {'A', 'B', 'C', 'D', 'E', 'H'}]
输出结果:
2
在网络分析中,最近邻子图被称为自我图(ego-graphs),在networkx这个库里,可以通过 nx.ego_graph(G, source, distance)
来获取。
import networkx as nx
G = nx.Graph()
G.add_edges_from(
[('A', 'B'), ('A', 'C'), ('D', 'B'), ('E', 'C'),
('H', 'C'), ('Y', 'I')])
pos = nx.spring_layout(G)
max_distance = 3
fig, axes = plt.subplots(1, max_distance, sharex=True, sharey=True)
for distance, ax in zip(range(max_distance), axes):
nx.draw_networkx(nx.ego_graph(G, "A", distance), pos=pos, ax=ax)
plt.show()