[Python] How to extract and plot the immediate neighbors (and the neighbors of neighbors) in a...

Discussão em 'Python' iniciado por Stack, Setembro 1, 2025.

  1. Stack

    Stack Membro Participativo

    Consider the following example

    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)


    [​IMG]

    I would like to extract and plot the subgraphs containing 'A' and all of neighbors, then all the neighbors of the neighbors, and so on n times (obtaining n different charts, that is). To be clear: step 0 is the node A itself, step 1 is the network B-A-C, step 2 is the network D-B-A-C-E-H (Y and I have been removed because they are not neighbors of neighbors of A).

    I have been unable to do so with networkx. Using all_neighbors() extracts all immediate neighbors (B and C) but somehow loses A in the process so the graph is incomplete.

    zn = G.subgraph(nx.all_neighbors(G, 'A'))
    nx.draw_networkx(zn)


    [​IMG]

    What can be done here?

    Continue reading...

Compartilhe esta Página