Search code examples
syntaxgraphvizdiagramdot

Graphviz connect nested subgraphs


Problem

Similarly to this question (GraphViz - How to connect subgraphs?) I would like to connect some sub-graphs. Only this time I need to connect nested sub-graphs... Graphviz seems unhappy with my syntax.

Source

digraph G {
        compound=true

        subgraph cluster_family1 {
                graph [ label="Family1"; ]
                subgraph cluster_genus1 {
                        graph [ label="Genus1"; ]
                        species_1
                        species_2
                }
                subgraph cluster_genus2 {
                        graph [ label="Genus2"; ]
                        species_3
                        species_4
                }
        }
        subgraph cluster_family2 {
                graph [ label="Family2"; ]
                subgraph cluster_genus2 {
                        graph [ label="Genus3"; ]
                        species_5
                        species_6
                }
        }
        species_2 -> species_3 [ lhead=cluster_genus1 ] # TODO: Fix this line!!
}

The resulting diagram does not have the desired subgraph arrow pointing that I was hoping for. Instead I get the error:

dot -Tsvg source.dot -o output.svg
Warning: Two clusters named cluster_genus2 - the second will be ignored
Warning: species_2 -> species_3: head not inside head cluster cluster_genus1

Solution

  • Two bugs:

    • duplicate cluster names: (cluster_genus2)
    • confused heads & tails of your edge

    You may want other tweaks, e.g if you want species_1 before species_2

    digraph G {
            compound=true
    
            subgraph cluster_family1 {
                    graph [ label="Family1"; ]
                    subgraph cluster_genus1 {
                            graph [ label="Genus1"; ]
                            species_1
                            species_2
                    }
                    subgraph cluster_genus2 {
                            graph [ label="Genus2"; ]
                            species_3
                            species_4
                    }
            }
            subgraph cluster_family2 {
                    graph [ label="Family2"; ]
                    subgraph cluster_genus3 {  // fixed duplicate name
                            graph [ label="Genus3"; ]
                            species_5
                            species_6
                    }
            }
            species_2 -> species_3 [ ltail=cluster_genus1 ] # changed head to tail??
    }
    

    Giving:
    enter image description here