0

I'm using Digraph from graphviz module in python to visualize a tree. I create nodes by Digraph.node() and create edges by Digraph.edge().

I want to specify which one should be right node and which one should be left node. But automatically it set first created node as left child and second created node as right child.

For example in this code:

from graphviz import Digraph

test = Digraph()

test.node('a')
test.node('b')
test.node('c')

test.edge('c', 'b')
test.edge('c', 'a')

test

Output is:

enter image description here

I want 'b' node be left child and 'a' node be right child like this:

enter image description here

I should emphasis I couldn't create 'b' node first then create 'a' node.

Is there any way to do this for me with this library or not? If there isn't any solution for this module, recommend another module please.

ariankazemi
  • 105
  • 3
  • 14
  • Does this answer your question? [How can I control within level node order in graphviz's dot?](https://stackoverflow.com/questions/44274518/how-can-i-control-within-level-node-order-in-graphvizs-dot) – Adam.Er8 May 11 '23 at 09:15
  • No, I want to implement it in python – ariankazemi May 11 '23 at 09:23

1 Answers1

1

This is a quite reasonable desire, but there is nothing in the python-to-graphviz interface (or in Graphviz itself) that explicitly sets both top-to-bottom and left-to-right positioning.
However, you can probably get the output you desire by doing some "extra" bookkeeping in your python program. Either:

  • create a stack/list in your python program of the edges you want to create, but then actually create them in the "reverse" order

or

  • create the edges in the "natural" order, but then use the "invisible edge" trick that is discussed in the link given above to explicitly tell Graphviz what order you want.

The first alternative is probably the easiest place to start, and may even result in a smaller and cleaner, but slightly more complex, program. Good luck.

sroush
  • 5,375
  • 2
  • 5
  • 11