Home > other >  python: rank attribute in graphviz to align nodes
python: rank attribute in graphviz to align nodes

Time:02-27

i'm trying to get my nodes to align in graphviz using the 'rank' attribute, but i'm not getting the desired result. i'm using graphviz in a jupyter notebook. here is my code:

import graphviz
from IPython.display import display

p = graphviz.Digraph(graph_attr={'rankdir':'LR'}, format='png')
p.node('A')
p.node('B')
p.node('D')
p.node('E')
p.node('F')
p.edges(['AB','BD', 'DE', 'EF'])

c = graphviz.Digraph(name='child',
                     graph_attr={'rankdir':'LR', 'rank':'min'},
                     node_attr={'shape': 'box'})

c.node('C')
c.edges(['AC', 'CD'])

p.subgraph(c)

p.render('p.gv', view=False)

with open("p.gv") as f:
    dot_graph = f.read()
    display(graphviz.Source(dot_graph))

so what I am trying to achieve is to have nodes 'A', 'B', 'D', 'E', and 'F' to all be in the same row aligned from left to right, and then node 'C' to be directly above node 'B'. I have embedded an image which shows the output from the current state of my code. Based on the image, I want to rotate the nodes 'A', 'B', and 'C' 90 degrees in the counterclockwise direction with node 'D' being the axis of rotation. Then, once that is accomplished, I want to switch the position of nodes 'B', and 'C'

I hope someone can help me.

Thanks

rendered graph

CodePudding user response:

Can't provide the Python version, but here is plain Graphviz. The trick is rank=same

digraph D {
  //   rankdir=LR //  nope
  C[shape=rect]
  {rank=same  // this puts all 5 nodes on same rank
  A->B  
  B->D
  D->E
  E->F
  }
  A->C->D  
}

Giving:
enter image description here

CodePudding user response:

thanks to @sroush, I was able to build Python code based on the Graphviz code that @sroush provided.

import graphviz
from IPython.display import display

p = graphviz.Digraph(format='png')
p.node('C', shape='box')

c = graphviz.Digraph(graph_attr={'rank':'same'})
c.node('A')
c.node('B')
c.node('D')
c.node('E')
c.node('F')
c.edges(['AB','BD', 'DE', 'EF'])
p.edges(['AC', 'CD'])

p.subgraph(c)

p.render('j.gv', view=False)

with open("j.gv") as f:
    dot_graph = f.read()
    display(graphviz.Source(dot_graph))

enter image description here

  • Related