如何在Graphviz Dot中创建从节点到同名子图的边?
搞定Graphviz节点指向同名子图的方法
嘿,我帮你梳理清楚怎么实现这条指向子图的边啦!核心是利用Graphviz的compound属性和子图ID引用,下面是完整的可运行代码和关键说明:
完整代码示例
digraph G { rankdir=LR; compound=true; graph [fontname="Liberation Mono"]; node [fontname="Liberation Mono"]; edge [fontname="Liberation Mono"]; subgraph cluster0 { label="System components"; mmp [label="Manufacturer of means of production", shape=box]; } // 给同名子图设置唯一的cluster ID(必须以cluster_开头才会渲染成带框的子图) subgraph cluster_mmp { label="Manufacturer of means of production"; // 这里可以添加子图内部的任意节点,比如生产环节、供应链之类的 production_line [label="Automated Production Line"]; supply_chain [label="Raw Material Supply"]; } // 关键:用lhead指定这条边指向的子图ID,实现节点到子图边框的连接 mmp -> cluster_mmp [lhead=cluster_mmp]; }
关键知识点拆解
compound=true是必须的:这个属性开启后,Graphviz才允许跨子图的边连接到子图的边界,不然只能连接具体节点。- 子图要设唯一ID:子图ID必须以
cluster_开头,这样Graphviz才会把它渲染成带边框的子图,而且ID要唯一,方便边引用。 - 用
lhead指定子图:在边的定义里加[lhead=子图ID],就能让边从节点直接连到目标子图的边框上,完美实现你要的效果。
如果之后你想让边指向子图内部的某个具体节点,直接把目标换成子图里的节点名称就行,比如mmp -> production_line。
内容的提问来源于stack exchange,提问作者Glory to Russia
相关产品推荐
相关产品推荐

