有个树状结构,想生成一幅对应的矢量图,可以用 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")
- 效果:

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

被折叠的 条评论
为什么被折叠?



