0

I am building trees that are designed to represent a flow from leaves to the root of the tree using the anytree package in python. I have the following code.

from anytree import Node
from anytree.exporter import DotExporter
A = Node('A')
B = Node('B', parent = A)
C = Node('C', parent = A)
DotExporter(A).to_picture('example.png')

And it produces the following image.

enter image description here

I want to modify this image such that the arrows point in the opposite direction. I know that in graphviz adding [dir=back] to an edge definition line will give me the result that I want. By running the following code:

for line in DotExporter(A):
    print(line)

I get the output:

digraph tree {
    "A";
    "B";
    "C";
    "A" -> "B";
    "A" -> "C";
}

But how do I modify the output of DotExporter from the anytree interface to add [dir=back] to the edge definition lines and reverse the direction of the arrows?

Max Feinberg
  • 810
  • 1
  • 6
  • 21

1 Answers1

1

To modify the edge attributes defined for Dot by the DotExporter you need to change the edgeattrfunc attribute of DotExporter as such.

from anytree import Node
from anytree.exporter import DotExporter
A = Node('A')
B = Node('B', parent = A)
C = Node('C', parent = A)
DotExporter(A, edgeattrfunc = lambda node, child: "dir=back").to_picture('example.png')

Looking at the output, you now get:

for line in DotExporter(A, edgeattrfunc = lambda node, child: "dir=back"):
    print(line)
digraph tree {
    "A";
    "B";
    "C";
    "A" -> "B" [dir=back];
    "A" -> "C" [dir=back];
}

Which produces the following image.

enter image description here

Max Feinberg
  • 810
  • 1
  • 6
  • 21