Python 如何仅从特定节点的邻接矩阵创建网络图?

Python 如何仅从特定节点的邻接矩阵创建网络图?,python,graph,networkx,gephi,Python,Graph,Networkx,Gephi,我有一个邻接矩阵5000X5000,我想创建一个网络图。需求是用户将输入节点,输出将是该特定输入节点的图形(1度和2度) 我已经尝试过使用Gephi,但由于邻接矩阵很大,我无法专注于每个节点。因此,我想知道是否可以为特定节点创建一个图(因为我只对每个节点的一级和二级连接感兴趣,而不感兴趣) Gephi是基于UI的,所以我没有代码 输入将是一个节点id,输出将是一个对应于该节点id(一级和二级连接)的图形 import networkx as nx import numpy as np # ma

我有一个邻接矩阵5000X5000,我想创建一个网络图。需求是用户将输入节点,输出将是该特定输入节点的图形(1度和2度)

我已经尝试过使用Gephi,但由于邻接矩阵很大,我无法专注于每个节点。因此,我想知道是否可以为特定节点创建一个图(因为我只对每个节点的一级和二级连接感兴趣,而不感兴趣)

Gephi是基于UI的,所以我没有代码


输入将是一个节点id,输出将是一个对应于该节点id(一级和二级连接)的图形

import networkx as nx
import numpy as np

# make dummy adjacency matrix
a = np.random.rand(100,100)
a = np.tril(a)
a = a>0.95

# make graph from adjaceny matrix
G = nx.from_numpy_matrix(a)


def neigh(G, node, depth):
    """ given starting node, recursively find neighbours
        until desired depth is reached
    """

    node_list = []
    if depth==0:
        node_list.append(node)
    else:
        for neighbor in G.neighbors(node):
            node_list.append(node)
            node_list += neigh(G, neighbor, depth-1)
    return list(set(node_list)) # intermediate conversion to set to lose duplicates. 

# a bit more compressed:
def neigh_short(G, node, depth):
    """ given starting node, recursively find neighbours
        until desired depth is reached
    """

    node_list = [node]
    if depth>0:
        for neighbor in G.neighbors(node)
            node_list += neigh_short(G, neighbor, depth-1)
    return list(set(node_list)) # intermediate conversion to set to lose duplicates. 

# example:
# find all neighbours with distance 2 from node 5:
n = neigh(G, node=5, depth=2)

# extract the respective subgraph from G and store in H
H = G.subgraph(n)

谢谢你的回复。这符合我的目的。一个轻微的修正。对于G.邻居(节点):节点列表。附加(邻居)节点列表+=neigh(G,邻居,深度-1)返回列表(集合(节点列表))#到Gephi拓扑过滤器文件夹中sSee“Ego网络”的中间转换。