Search code examples
python-3.xplotgraphvizdot

How to format edge labels in Graphviz?


I created a graphviz plot to visualize a decision tree. Now I would like to add labels (e.g. True, False) to the graph on all edges.

I was using regex to manipulate the .dot file, adding the labels True and False manually. Resulting in the following file

digraph Tree {
node [shape=box, style="rounded", color="black", fontname=helvetica] ;
edge [fontname=helvetica] ;
0 [label="s5 smaller
or equal to 0.0"] ;
1 [label="bmi smaller
or equal to 0.0"] ;
0 -> 1 [labeldistance=2.5, labelangle=45, headlabel="True"] ;
3 [label="value = 110.6"] ;
1 -> 3 [headlabel="True"] ;
4 [label="value = 161.0"] ;
1 -> 4 [headlabel="False"] ;
2 [label="bmi smaller
or equal to 0.0"] ;
0 -> 2 [labeldistance=2.5, labelangle=-45, headlabel="False"] ;
5 [label="value = 174.0"] ;
2 -> 5 [headlabel="True"] ;
6 [label="value = 237.7"] ;
2 -> 6 [headlabel="False"] ;
}

This produces the following plot:

enter image description here

However, the labels don’t get nicely arranged (the arrow cuts-off the label) and I would like to format the text accordingly. Is there a way this can be done in graphviz plots? Thank you!


Solution

  • [A more complete (and messy) answer]
    There are multiple levels of label formatting:

    • You can insert spaces to influence X position
    • you can insert actual newlines or \n to influence Y position
    • you can use \l and \r to force left or right justification
    • you can use (pseudo) HTML strings to add more formatting combinations
    • or you can explicitly set X and Y position by setting or modifying the lp attribute of a node or edge.

    see:

    for explicit positioning

    Examples:

    digraph labels {
      a [label=a]
      b [label="b\n\n\n"]
      c [label="       c"]
      d [label="d\n\nD"]
      e [label=<<B>e</B>>]
      f
      r [label=<<table><tr><td>r</td></tr></table>>]
      s
      
      a->b [label=a123]
      b->c [label="b123\n\n\n b321"]
      c->d [label="       c123"]
      d->e [label=" d123\n\nD123"]
      e->f [label=<<I>  e123</I>>]
    
      r->s [label=<<table><tr><td>r123</td><td>6</td></tr><tr><td></td><td>r321</td></tr></table>>]
    }
    

    enter image description here