Home > other >  Adjusting node numbering in Networkx
Adjusting node numbering in Networkx

Time:07-11

The following code generate adjacency matrix of a specific network. However, I want the node numbering to occur in a certain way and remain fixed and not fluctuate with every run. I present the current and expected output.

import matplotlib.pyplot as plt
import networkx as nx


N = 2

G = nx.Graph()
for u in range(2 * N * (N   1)):
    if u % (2 * N   1) < N:
        for v in (u - 2 * N - 1, u - N - 1, u - N):
            if G.has_node(v):
                G.add_edge(u, v)
    elif u % (2 * N   1) == N:
        G.add_edge(u, u - N)
    elif u % (2 * N   1) < 2 * N:
        for v in (u - 1, u - N - 1, u - N):
            G.add_edge(u, v)
    else:
        for v in (u - 1, u - N - 1):
            G.add_edge(u, v)
            
A=nx.adjacency_matrix(G).todense()
print([A])
nx.draw(G,with_labels=True, font_weight='bold')

The current output is

enter image description here

The expected output is

enter image description here

CodePudding user response:

Here is a possible solution:

import networkx as nx

N = 2

def pos():
    x, y = 1, N   3 - 1
    for _ in range(2 * N * (N   1)):
        yield (x, y)
        y -= (x   2) // (N   3)
        x = (x   2) % (N   3)

G = nx.Graph()
it_pos = pos()
for u in range(2 * N * (N   1)):
    G.add_node(u   1, pos=next(it_pos))
    if u % (2 * N   1) < N:
        for v in (u - 2 * N - 1, u - N - 1, u - N):
            if G.has_node(v   1):
                G.add_edge(u   1, v   1)
    elif u % (2 * N   1) == N:
        G.add_edge(u   1, u - N   1)
    elif u % (2 * N   1) < 2 * N:
        for v in (u - 1, u - N - 1, u - N):
            G.add_edge(u   1, v   1)
    else:
        for v in (u - 1, u - N - 1):
            G.add_edge(u   1, v   1)

nx.draw(G, nx.get_node_attributes(G, 'pos'), with_labels=True, font_weight='bold')

This is the result of the code above: enter image description here Here I've used the pos() function to generate each node position. These positions are saved as tuples (x, y) within each node as a label. And they're eventually used to draw the graph.

  • Related