如何提取并绘制networkx图中的直接邻居及其邻居?

1 投票
3 回答
53 浏览
提问于 2025-04-14 18:33

考虑下面这个例子

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'及其所有邻居的子图,然后再提取邻居的邻居,依此类推,进行次(也就是说,得到个不同的图表)。为了更清楚:第0步是节点本身,第1步是网络,第2步是网络被去掉了,因为它们不是的邻居的邻居)。

我在使用时遇到了困难。使用可以提取所有直接邻居(),但在这个过程中不知怎么的把给丢掉了,所以图是不完整的。

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()

在这里输入图片描述

撰写回答