Home > Mobile >  Keeping the orientation same of graphs in Networkx
Keeping the orientation same of graphs in Networkx

Time:07-14

I am generating a graph with 12 nodes and the adjacency matrix. However, with every run, I see a different orientation though the adjacency matrix is the same. I want to have the same orientation (with the same adjacency matrix ofcourse!) in every run. I present the current and expected output.

import networkx as nx
import numpy as np
import matplotlib
import matplotlib.pyplot as plt

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

D=len(G.nodes)
print(D)

fig, ax = plt.subplots(1, 1)
P=np.array([[1.00000000e-04, 1.90053824e-05, 3.70041863e-05, 5.50029902e-05,
        7.30017941e-05, 8.20011961e-05, 1.00059804e-05, 9.10005980e-05,
        2.80047843e-05, 1.00657843e-06, 4.60035882e-05, 1.01000000e-04]])
D=nx.draw(G, with_labels=True, node_color=[P], node_size=1000, cmap='Blues')

# -------------------------------------
norm = matplotlib.colors.Normalize(vmin=np.min(P), vmax=np.max(P))
sm = plt.cm.ScalarMappable(cmap='Blues', norm=norm)
sm.set_array([])
clb=fig.colorbar(sm)
clb.set_label('r (m)',labelpad=-50, y=1.1, rotation=0)
# -------------------------------------
plt.show()

The current output is

enter image description here

The expected output is

enter image description here

CodePudding user response:

You are plotting twice with nx.draw, the first time with the node positions specified (correctly), the second time without specifying the node positions. Presumably, you are only saving (and hence seeing) the second plot.

Delete the first call to nx.draw and substitute the second call (D=nx.draw(...)) with:

nx.draw(G, nx.get_node_attributes(G, 'pos'), with_labels=True, font_weight='bold', node_color=[P], cmap='Blues')

enter image description here

  • Related