如何在Dot语言的子图中控制节点排列顺序
解决Dot图中节点顺序不符合预期的问题
问题描述
我无法让节点按照编写的顺序显示。以下是我使用Dot语言编写的代码:
digraph G { fontname = "Hilda 10" rankdir=LR splines=line nodesep=.08; ranksep=1; edge [color=black, arrowsize=.5]; node [fixedsize=true,style=filled,color=none,fillcolor=gray,shape=circle,fontcolor=black] subgraph cluster_0 { color=none; node [style=filled, color=white, penwidth=15,fillcolor=gray shape=circle]; { l10 l11 } label = Input; } subgraph cluster_1 { color=none; node [style=filled, color=white, penwidth=15,fillcolor=gray shape=circle]; { l20 l21 l22 } label = Output; } l10 -> l20; l10 -> l21; l10 -> l22; l11 -> l20; l11 -> l21; l11 -> l22; }
我希望第二列(Output集群)的节点顺序为l20在上,l21和l22在下,但实际生成的图中l21在上、l20在下。尝试过设置rankdir=TB,以及添加隐形边rank=same l20 -> l21 -> l22 [style = invis]并设置edge [constraint=false],但这样第一列的节点会失去垂直居中效果。
解决方案
可以通过在Output集群内添加带约束控制的隐形边来强制节点垂直顺序,同时保留原有边的布局约束,避免第一列节点失去居中效果。修改后的代码如下:
digraph G { fontname = "Hilda 10" rankdir=LR splines=line nodesep=.08; ranksep=1; edge [color=black, arrowsize=.5]; node [fixedsize=true,style=filled,color=none,fillcolor=gray,shape=circle,fontcolor=black] subgraph cluster_0 { color=none; node [style=filled, color=white, penwidth=15,fillcolor=gray, shape=circle]; { l10 l11 } label = Input; } subgraph cluster_1 { color=none; node [style=filled, color=white, penwidth=15,fillcolor=gray, shape=circle]; // 隐形边强制垂直顺序,constraint=false避免影响水平rank布局 l20 -> l21 [style=invis, constraint=false]; l21 -> l22 [style=invis, constraint=false]; { l20 l21 l22 } label = Output; } l10 -> l20; l10 -> l21; l10 -> l22; l11 -> l20; l11 -> l21; l11 -> l22; }
关键说明
- 隐形边
l20 -> l21和l21 -> l22会强制Dot按照指定顺序垂直排列节点,确保l20在上,l21居中,l22在下。 constraint=false属性让这些隐形边不会影响节点的水平rank(LR方向下,rank对应列的位置),因此Output集群的节点依然会保持在第二列。- 原有连接边的约束未被修改,所以第一列的Input节点会继续保持垂直居中的布局效果。
内容的提问来源于stack exchange,提问作者douglasbr
相关产品推荐
相关产品推荐

