Reputation: 1063
What i Have : a multigraph with four nodes and four edge. Each node has a position specified (the nodes form a squadre structure)
What i want: drawing the multigraph with nodes posistions.
PROBLEM: Positions are ignored in the final layout.
This is my code :
import networkx as nx
import pydot
from my_lib import *
graph= nx.MultiGraph()
#add 4 nodes in the vertexs of a square. X and Y are the coordinates
graph.add_node(1,x=10,y=10)
graph.add_node(2,x=10,y=20)
graph.add_node(3,x=20,y=10)
graph.add_node(4,x=20,y=20)
graph.add_edge(1,2)
graph.add_edge(2,3)
graph.add_edge(3,4)
graph.add_edge(4,1)
#transform the multigraph in pydot for draw it
graphDot=nx.to_pydot(graph)
#change some attribute for the draw, like shape of nodes and the position of nodes
for node in graphDot.get_nodes():
node.set_shape('circle')
#getAttrDot is a function that returns the value of attribute passed
pos_string='\''+ get_attrDot(node,'x')+','+get_attrDot(node,'y')+'!\''
print 'coordinate: ' + pos_string #the pos_string printed is correct form: 'x,y!'
node.set('pos',pos_string)
graphDot.write_png('test_position.png')
Here the result of this code.
The image 'test_position.png' is :[1]: https://i.sstatic.net/UfiEv.jpg
As you can see, the node positions are ignored.
Can you help me please? Thanks!
EDIT SOLVED: The suggest of Aric solved my problem. THANKS!!!
Upvotes: 2
Views: 1350
Reputation: 25289
You can set the attributes before you convert the graph to a Pydot object:
import networkx as nx
graph= nx.MultiGraph()
#add 4 nodes in the vertexs of a square. X and Y are the coordinates
graph.add_node(1,x=100,y=100)
graph.add_node(2,x=100,y=200)
graph.add_node(3,x=200,y=100)
graph.add_node(4,x=200,y=200)
graph.add_edge(1,2)
graph.add_edge(2,3)
graph.add_edge(3,4)
graph.add_edge(4,1)
# assign positions
for n in graph:
graph.node[n]['pos'] = '"%d,%d"'%(graph.node[n]['x'], graph.node[n]['y'])
p = nx.to_pydot(graph)
print p.to_string()
p.write('foo.dot')
# run neato -n2 -Tpng foo.dot >foo.png
The output is:
graph G {
1 [y=100, x=100, pos="100,100"];
2 [y=200, x=100, pos="100,200"];
3 [y=100, x=200, pos="200,100"];
4 [y=200, x=200, pos="200,200"];
1 -- 2 [key=0];
1 -- 4 [key=0];
2 -- 3 [key=0];
3 -- 4 [key=0];
}
Run
neato -n2 -Tpng foo.dot >foo.png
(the -n2 keeps your node positions)
Upvotes: 2