Graphs in Perl

It wasn’t until recently that I started to really use perl for my tasks. But the more I use it, the more I find myself enjoy­ing it’s sim­ple ele­gance and easy meth­ods for trans­form­ing large com­plex sets of data into some­thing mean­ing­ful. When­ever I find my self needed to ana­lyze logs, I like to see them in the con­text of over time. This is far from the only way to visu­al­ize data, but it’s a basic one that I find use­ful time and time again. GD::Graph makes this task insanely easy.

All that’s required for a basic graph is a two-dimensional array. Essen­tially, an array con­tain­ing two other arrays; one for the X-Axis val­ues, and another for the Y-Axis. The lit­tle code below cre­ates my data array, and sets the width/height of a new graph object.

@data = (\@xvalues,\@yvalues);
my $graph = GD::Graph::area->new($width,$height);

Now all I need to do is plot the data on the graph object and extract a pic­ture from it.

my $image = $graph->plot(\@data) or die $graph->error;
print STDOUT $image->png;

And that’s it!  A very easy and straight for­ward method to get a sim­ple graph of some data.

Leave a Reply