Automatic multiline labels in Graphviz?

One person wrote a Perl script to achieve this. I found it in his blog: Text wrapping with dot (graphviz).

⚠ Note

This only works if the labels are in the format node [ label=”node label” ]. If the nodes are declared directly (e.g. ”node label”) then it doesn’t work

Perl script:

#!/usr/bin/perl
use strict;
 
my $usage = "setdotlabelwidth [char-width] < [dotfile]";
my $width = shift() or die("Usage: $usage $!");
 
while(<STDIN>)
{
  if(m/label="(.*?)"/)
  {
    my $labeltext = $1;
    my @words = split(/ /, $labeltext);
    my @newtext = ();
    my $newline = "";
    foreach my $word(@words)
    {
      if( length($newline) > 0 and
          length($newline) + length($word) > $width )
      {
        push(@newtext, $newline);
        $newline = "";
      }
      $newline .= " " if( length($newline) > 0 );
      $newline .= $word;
    }
    push(@newtext, $newline) if( length($newline) > 0 );
    my $newlabel = join("\\n", @newtext);
    s/label=".*?"/label="$newlabel"/;
  }
  print;
}

Save this program as setdotlabelwidth, then simply pipe the output into GraphViz. If for example you want to set the width to 35 characters, then the command is:

./setdotlabelwidth 35 < tile-error-correction.dot | dot -Tpng -o tile-error-correction.png

Before: After:


Yes, HTML-like labels (<...>) support
tag, using which you can break the lines. E.g.

"A" -> "B"
[label = <1. <br/>
 2. <br/>
 3. <br/>
 4. <br/>
 .... <br/> 
> color="blue" style="dashed"];

These also work when embedding Graphviz in LaTeX, where \n would not.


I've also searched for this, but I don't think it's possible in the current version. The current "solution" is to write code that automatically adds the "\n" every few characters, based on the minimum distance between nodes (nodesep attribute, if I'm not mistaken).

Tags:

Graphviz