Search code examples
graphvizsubgraph

Align the nodes when using subgraphs in Graphviz


I want to align the nodes when using subgraphs in Graphviz.

It works perfectly well in a plot without subgraphs. But when I introduce subgraphs there is a (unexpected ?) shift of the nodes.

Here is a simple example.

digraph My_test_without_subgraphs {

  graph [overlap = true, compound = true, rankdir = LR]

  node [shape = box, color = lightgrey, style = filled, fontcolor = black]
  T1 [label = 'my task 1']
  T2 [label = 'my task 2']
  T3 [label = 'my task 3']
  T4 [label = 'my task 4']

  T1 -> T3
  T2 -> T3
  T3 -> T4

}

digraph My_test_with_subgraphs {

  graph [overlap = true, compound = true, rankdir = LR]

  node [shape = box, color = lightgrey, style = filled, fontcolor = black]
  T1 [label = 'my task 1']
  T2 [label = 'my task 2']
  T3 [label = 'my task 3']
  T4 [label = 'my task 4']

  subgraph cluster1 {
  label = 'cluster 1'
  color = cornsilk
  style = filled
  T1 -> T3
  T2 -> T3
  }

  subgraph cluster2 {
    label = 'cluster 2'
    color = cornsilk
    style = filled
    T3 -> T4
  }
}

Solution

  • Yes, margin does the trick. The value itself is not so important, as long it is a number smaller 8.

    By the way please use " instead of ', some interpreters, esp. the online editors, would raises an error.

    digraph My_test_without_subgraphs {
    
      graph [overlap = true, compound = true, rankdir = LR]
    
      node [shape = box, color = lightgrey, style = filled, fontcolor = black]
      T1 [label = "my task 1"]
      T2 [label = "my task 2"]
      T3 [label = "my task 3"]
      T4 [label = "my task 4"]
    
      T1 -> T3
      T2 -> T3
      T3 -> T4
    
    }
    

    Results in: graph1

    and

    digraph My_test_with_subgraphs {
    
      graph [overlap = true, compound = true, rankdir = LR]
    
      node [shape = box, color = lightgrey, style = filled, fontcolor = black]
      T1 [label = "my task 1"]
      T2 [label = "my task 2"]
      T3 [label = "my task 3"]
      T4 [label = "my task 4"]
    
      subgraph cluster1 {
      label = "cluster 1"
      color = cornsilk
      style = filled
      T1 -> T3
      T2 -> T3
      }
    
      subgraph cluster2 {
        margin = 6
        label = "cluster 2"
        color = cornsilk
        style = filled
        T3 -> T4
      }
    }
    

    results in graph2