Here is another chapter of my love-hate relationship with Perl: A couple of people recently asked me about drawing graphs, like the guide-tree diagrams I’m generating as part of my diploma thesis, and they were amazed how nice and easy to use the GraphViz tools and the corresponding Perl module are. So here is the example I’ve come put together. It doesn’t really tell you anything that you couldn’t get from the excellent documentation, but people don’t like reading documentation no matter how well written it is, and I suppose it does solve a rather common problem. -So here is the code:
use GraphViz;
#create your adjacency matrix and nodes, do whatever else you need done.
my @admat = (
[1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0],
[0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0],
[0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
);
my @nodes=(’1′, ‘2′, ‘3′, ‘4′, ‘5′, ‘6′, ‘7′, ‘8′, ‘9′, ‘10′, ‘11′, ‘12′);
#create a new graph
my $graph = GraphViz->new();
#add all your nodes to the graph
foreach (@nodes) {
$graph->add_node($_);
}
#create edges as defined by your adjacecncy matrix
for($i=0; $i< @nodes; $i++){
for($j=0; $j<@nodes; $j++){
if($admat[$i][$j] eq 1){
$graph->add_edge($nodes[$i] => $nodes[$j]);}
}
}
#render the graph to a png-file
$graph->as_png(”pretty.png”);
It produces this picture:










