0

I am using PyGraphviz to generate a hierarchical tree like structure with several levels and nodes. Whenever I try to create an edge between two nodes (I have unique index assigned to every node in the tree), Pygraphviz generates two edges, considering both the actual node value and the index whereas I am expecting from it, to only create an edge between node unique indices. Please look at the example code and figure below.

Sample code:

from pygraphviz import *

word_link = []
A = AGraph(directed=True)
ind = 0
A.add_node(ind, color='lightskyblue', style='filled', label='Root', shape='box')
sen_ind = ind + 1
# sentence 1
A.add_node(sen_ind, color='lightcoral', style='filled', label=0, shape='box')
A.add_edge(ind, sen_ind, color='plum', style='filled')
word_ind = sen_ind + 1
# word 1
A.add_node(word_ind, color='lightsalmon', style='filled', shape='box', label=0)
word_link.append(word_ind)
A.add_edge(sen_ind, word_ind, color='plum', style='filled')
word_ind += 1
# word 2
A.add_node(word_ind, color='lightsalmon', style='filled', shape='box', label=1)
A.add_edge(sen_ind, word_ind, color='plum', style='filled')
sen_ind = word_ind + 1
# sentence 2
A.add_node(sen_ind, color='lightcoral', style='filled', label=1, shape='box')
A.add_edge(ind, sen_ind, color='plum', style='filled')
word_ind = sen_ind + 1
# word 1
A.add_node(word_ind, color='lightsalmon', style='filled', label=0, shape='box')
A.add_edge(sen_ind, word_ind, color='plum', style='filled')
word_ind += 1
# word 2
A.add_node(word_ind, color='lightsalmon', style='filled', label=1, shape='box')
word_link.append(word_ind)
A.add_edge(sen_ind, word_ind, color='plum', style='filled')

# doesn't work | need a fix
A.add_edge(word_link[0], word_link[1], color='sienna', style='filled')

A.layout()  # layout with default (neato)
A.draw('simple.png',prog='dot') # draw png

Tree generated with duplicate edges enter image description here

Expected Figure: enter image description here

Shankar
  • 3,496
  • 6
  • 25
  • 40

2 Answers2

1

Try adding constraint=False:

A.add_edge(word_link[0], word_link[1], constraint=False, color='sienna', style='filled')
marapet
  • 54,856
  • 12
  • 170
  • 184
  • thanks! that works but the edge is on top of the nodes. How to make it run below the nodes? – Shankar Apr 05 '13 at 23:20
  • Since there are no nodes below, I guess graphivz tries not to make the graph larger than needed. You could try to use [compass points](http://www.graphviz.org/content/attrs#kportPos) to force the edge to leave and enter the node on the `s` side (bottom) of the node (add `tailport="s"` or `tailport="se"` and `headport="s"` or `headport="sw"`). – marapet Apr 06 '13 at 08:48
0

You can also try to define ranks (levels)

see this answer another use gave me for a similar question:

Pygraphviz / networkx set node level or layer

Community
  • 1
  • 1
Dr Sokoban
  • 1,638
  • 4
  • 20
  • 34