python - 如何从邻接矩阵仅针对特定节点创建网络图?

标签 python graph networkx gephi

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

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

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

输入将是一个node_id,输出将是与该node_id对应的图(第一和第二度连接)

最佳答案

这是使用 networkx 的实现:

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)

关于python - 如何从邻接矩阵仅针对特定节点创建网络图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57734399/

相关文章:

python - 如何将值从 1 列分配给另一列并在 Pandas 中发出警告

Python 将特定列表的列表连接到数据帧

javascript - 使用具有特定移动规则的 DFS 生成迷宫

python - NetworkX - 保持边缘秩序

python - 为什么会出现 TypeError : 'module' object is not callable when trying to import the random module?

python - 使用 Python 排列列表

algorithm - 避免图中的边相交

ios - 如何显示x轴标题?

python - Networkx 读取军械调查 - ITN 综合传输网络?/读取 GML 文件

python-3.x - 如何将数据框中的每一行转换为具有属性的节点?