Graphviz可视化有向图

有个树状结构,想生成一幅对应的矢量图,可以用 Graphviz[1]。装好之后把 bin/ 目录加入 PATH,敲 dot --help 命令测试。

Basic Usage

语法类似 markdown 用 mermaid。将图结构写成一个 test.dot 文件:

digraph graph_name {
a->b;
b->d;
c->d;
}

其中 digraph 指明是有向图;由于没有孤立点,所以可以不用独立声明。

然后用 dot -Tpng test.dot -o test.png 生成 .png,或 dot -Tpdf test.dot -o test.pdf 生成 .pdf。

Code

一个 python 例程,将结构写进 .dot 文件,并生成 .png 和 .pdf。

import os


tree = [
    ["organism", [
        ["animals", [
            "bird",
            "dog"
        ]], # animals
        ["people", [
            "baby",
            "female",
            "male",
        ]], # people
        ["plant", [
            "flower",
            "tree"
        ]], # plant_life
    ]], # organism
]


def show_tree(T, layer=0):
	"""展示树状结构,debug 用"""
    for c in T:
        if layer > 0:
            print("|  " * (layer - 1) + "|- ", end="")
        if isinstance(c, str):
            print(c)
        elif isinstance(c, list):
            hyper, hypo_list = c
            print(hyper)
            show_tree(hypo_list, layer+1)


def write_graph(T, _file, fa=None):
	"""写入 .dot 文件"""
    for c in T:
        if isinstance(c, str):
            if fa is not None:
                _file.write("{}->{};\n".format(fa, c))
        elif isinstance(c, list):
            hyper, hypo_list = c
            if fa is not None:
                _file.write("{}->{};\n".format(fa, hyper))
            write_graph(hypo_list, _file, hyper)


# 打印 tree
show_tree(tree)

# 写入 .dot
with open("test.dot", "w") as f:
    f.write("digraph {} {{\n".format("graph_name"))
    write_graph(tree, f)
    f.write("}\n")

# 生成 .pdf
os.system("dot -Tpdf test.dot -o test.pdf")
# 生成 .png
os.system("dot -Tpng test.dot -o test.png")
  • 效果:

tree.png

References

  1. Graphviz
  2. 十分钟学会graphviz画图
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值