'Assigning value to graph nodes in Python
I am generating a 2D graph with adjacency matrix. I would like to assign the values of the nodes (1-9) with matrix P1. Node 1 is assigned 1.09730075, 2 is assigned 0.30837859, 3 is assigned 1.59680266, 4 is assigned 1.26296281 and so on...
import numpy as np
import networkx as nx
G = nx.grid_2d_graph(3,3)
new_nodes = {e: n for n, e in enumerate(G.nodes, start=1)}
new_edges = [(new_nodes[e1], new_nodes[e2]) for e1, e2 in G.edges]
G = nx.Graph()
G.add_edges_from(new_edges)
nx.draw(G, with_labels=True)
A1 = nx.adjacency_matrix(G)
A=A1.toarray()
print([A]) #for obtaining a random adjacency matrix
P1=np.array([[1.09730075, 0.30837859, 1.59680266],
[1.26296281, 0.57485091, 1.17281021],
[1.37259558, 1.33184676, 0.64522432]])
Solution 1:[1]
I'm not familiar with networkx, but from what I understood, this might be what you're looking for:
import numpy as np
import networkx as nx
P1 = np.array([[1.09730075, 0.30837859, 1.59680266],
[1.26296281, 0.57485091, 1.17281021],
[1.37259558, 1.33184676, 0.64522432]])
G = nx.grid_2d_graph(3, 3)
new_nodes = {e: P1[n // 3, n % 3] for n, e in enumerate(G.nodes)}
new_edges = [(new_nodes[e1], new_nodes[e2]) for e1, e2 in G.edges]
G = nx.Graph()
G.add_edges_from(new_edges)
nx.draw(G, with_labels=True
When creating new_nodes, it uses the value of n to identify which position of np array to index, and uses the weight specified at that position.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dilith Jayakody |

