【问题标题】:How do I reverse the direction of arrows in my python anytree graphviz output?如何在我的 python anytree graphviz 输出中反转箭头的方向?
【发布时间】:2020-04-24 19:50:21
【问题描述】:

我正在使用 python 中的 anytree 包构建旨在表示从叶子到树根的流的树。我有以下代码。

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')

它会生成以下图像。

我想修改此图像,使箭头指向相反的方向。 我知道在 graphviz 中将 [dir=back] 添加到边缘定义线会给我想要的结果。通过运行以下代码:

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

我得到了输出:

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

但是如何修改anytree界面中DotExporter的输出,将[dir=back]添加到边缘定义线并反转箭头方向?

【问题讨论】:

    标签: python graphviz dot anytree


    【解决方案1】:

    要修改由DotExporterDot 定义的边缘属性,您需要更改DotExporteredgeattrfunc 属性。

    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')
    

    查看输出,您现在得到:

    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];
    }
    

    这会产生以下图像。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-16
      • 2018-11-22
      • 1970-01-01
      • 2018-02-17
      • 2021-05-19
      相关资源
      最近更新 更多