luisfelipe18
luisfelipe18

Reputation: 597

Setting node locations with a dictionary

I have a dictionary with the following data:

pos = {0: (1,1), 1: (2,2), 2: (3,2), 3: (4,3)}

Then, I tried the following code:

import networkx as nx
G = nx.Graph()
G.add_nodes_from(pos)
#also G.add_nodes_from(pos.keys())
print(G.nodes(True))

which gives:

>>>> [(0, {}), (1, {}), (2, {}), (3, {})]

as you see, the positions are empty.

But if I write

G = nx.random_geometric_graph(5, 0.50)
print(G.nodes(True))

it returns

[(0, {'pos': [0.895101164279736, 0.43929155577155976]}), (1, {'pos': [0.006064168598946429, 0.6044775286563574]}), (2, {'pos': [0.021659978032451344, 0.47877598747213523]}), (3, {'pos': [0.05130150282000934, 0.1137451989310001]}), (4, {'pos': [0.8734509206210705, 0.9839817045923323]})]

it is, a graph with locations. Also I tried changing ´pos´ to ´pos2´ :

pos2 = {0:{'pos': [1,1]}, 1: {'pos':[2,2]}, 2: {'pos':[3,2]}, 3: {'pos':[4,3]}}

and I tried too the codes from other related questions:

1) answer1

for n, p in pos.iteritems():
    X.node[n]['pos'] = p

2) answer2

pos={'0':(1,0),'1':(1,1),'2':(2,3),'3':(3,2),'4':(0.76,1.80),'5':(0,2)}    

nx.set_node_attributes(G, 'coord', pos)

I have to add more than 1500 nodes to a graph with labels multiple times, so I dont want to use a ´for´ loop, I'm looking for efficient asigment, not like:

G2.add_node(1,pos=(1,0))

Can anyone find a way?

Upvotes: 1

Views: 390

Answers (1)

yatu
yatu

Reputation: 88236

You can set all nodes' position attributes at once through function.set_node_attributes, which takes a values parameter that can be a dictionary with the structure {node0: {'attr1': 20, 'attr2': 'nothing'}, node1: {'attr2': 3}}. Hence in this example you could directly do:

G = nx.Graph()
G.add_nodes_from(pos)
G.nodes(True)
# NodeDataView({0: {}, 1: {}, 2: {}, 3: {}})

Now we can feed function.set_node_attributes directly the dictionary as:

pos = {0: (1,1), 1: (2,2), 2: (3,2), 3: (4,3)}
nx.set_node_attributes(G, pos, 'pos')

And now by printing the NodeDataView you'd get:

G.nodes(True)
# NodeDataView({0: {'pos': (1, 1)}, 1: {'pos': (2, 2)}, 2: {'pos': (3, 2)}, 3: {'pos': (4, 3)}})

So if you were to draw the graph, you could set the positions in the pos parameter of nx.draw:

nx.draw(G, node_color='lightblue', with_labels=True, pos=pos, node_size=500)

enter image description here

Upvotes: 1

Related Questions