Search code examples
layoutgraphviz

How do I make a dot graph representing a binary tree more symmetric?


While trying to use Graphviz to create graphs for binary trees I've encountered many times a problem; apparently, with a high enough tree and a large enough nodesep the resulting graph tends not to be symmetric. As an example, here's a dot source

digraph G {
    nodesep=0.8;
    ranksep=0.5;

    {node[style=invis,label=""]; cx_30;
    }

    {rank=same; 20; 45; cx_30}
    {rank=same; 10; 25;}
    {rank=same; 40; 50}

    30 -> 20;
    30 -> 45;
    20 -> 10;
    20 -> 25;

    45 -> 40;
    45 -> 50;

    {edge[style=invis];
                        //Distantiate nodes
                        30 -> cx_30;
                            20 -> cx_30 -> 45;

                        //Force ordering between childs
                        10:e -> 25:w;
                        40:e -> 50:w;
    } 
} 

with the corresponding output (compiled with dot -Tpng file.dot > file.png) dot tree result

As you can see, 45 isn't placed in the middle between 40 and 50. I could use invisible nodes between 40 and 50 to correct the situation, but the resulting spacing would be too wide.

Am I doing something wrong? Is there a way to correct the situation?


Solution

  • Even though it didn't directly work for me, I'm passing the advice of Tom Ron to look at this answer about binary trees; the provided script didn't work for me, but the faq entry linked there helped me solve the problem; I didn't want to add an invisibile node for spacing reasons, but specifying a correct width attribute for the invisible nodes and scaling nodesep consequently works just fine.

    Here's a corrected source:

    digraph G {
        nodesep=0.4; //was 0.8
        ranksep=0.5;
    
        {node[style=invis,label=""]; cx_30;
        }
        {node[style=invis, label="", width=.1]; ocx_45; ocx_20;
        }
    
        {rank=same; 20; 45; cx_30}
        {rank=same; 10; 25; ocx_20}
        {rank=same; 40; 50; ocx_45}
    
        30 -> 20;
        30 -> 45;
        20 -> 10;
        20 -> 25;
    
        45 -> 40;
        45 -> 50;
    
        {edge[style=invis];
                            //Distantiate nodes
                            30 -> cx_30;
                                20 -> cx_30 -> 45;
    
                            //Force ordering between children
                            45 -> ocx_45;
                                40 -> ocx_45 -> 50;
                            20 -> ocx_20;
                                10 -> ocx_20 -> 25;
        } 
    } 
    

    with the corresponding output dot tree output