Home > Mobile >  Add position to a NetworkX graph using dictionary
Add position to a NetworkX graph using dictionary

Time:11-29

I have a DiGraph object called G1, a graph network with edges. G1 is composed by a list of nodes and I want to give them coordinates stored in a python dictionary.

This is the list of nodes: LIST OF NODES

For every node I have built a python dictionary with node's name as keys and a tuple of coordinates as values:

DICTIONARY WITH COORDINATES

I want to add the attribute position (pos) to every node with those coordinates.

At the moment I have tried using this cycle:

FOR LOOP TO ADD COORDINATES

But as a result only the last node appears to have coordinates, it seems like the data are being subscribed with this method:

ERROR

The result should be a graph network plotted on a xy space with the right coordinates obtained with the code: PLOT THE GRAPH I am obtaining the following error:

KeyError: (78.44, 88.3)

CodePudding user response:

I think it's mostly syntax errors here. Try this:

for node, pos in avg.items():
    G1.nodes[node]['pos'] = pos

Then, when building your visual, build your list of positions beforehand like this and just use the pos=pos convention when calling nx.draw().

pos = {node: G.nodes[node]['pos'] for node in G.nodes()}

**** EDIT: ****

There's a built-in way to do this that is much cleaner:

nx.set_node_attributes(G1, avg, 'pos')

Then, when drawing, use:

nx.draw(G1, pos=nx.get_nodes_attributes(G1, 'pos'))
  • Related