Graphviz可视化有向图

这篇博客介绍了如何利用Graphviz工具生成树状结构的矢量图。首先,需要安装Graphviz并将其bin目录添加到PATH环境变量中。接着,通过编写DOT语言描述图的结构,例如创建一个digraph,定义节点之间的关系。示例代码展示了如何用Python将树形数据结构写入.dot文件,然后调用dot命令生成.png和.pdf格式的图像。博客还提供了一个具体的树形数据结构示例和相应的Python代码来展示和写入.dot文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有个树状结构,想生成一幅对应的矢量图,可以用 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、付费专栏及课程。

余额充值