Five Things You Didn't Know You Could Do with Perl - ' Generating Graphs ' (
Page 5 of 6 )
Generating Graphs
Perl is often used to manipulate information and one of the best ways to show numerical data is through a graph. But did you realize you could generates those graphs from within Perl?
Using GD::Graph, we take a simple array of values and turn it into a graph. In the sample below I've imported the data from a file, but you could just as easily generate the information from a database table or any other data source. I also generate a file, simply called graph.png, but you could modify the script to generate a graph dynamically straight to browser as part of a Web page.
ADVERTISEMENT
The GD::Graph module is at the same time very flexible and also self-managing. You can specify as little or as much when defining the format of the graph, including setting minimum and maximum values, configuring how many X value items to include (or skip) in the axes title. Alternatively, you can specify nothing and let GD::Graph choose some suitable values for you.
use strict;
use GD;
use GD::Text;
use GD::Graph::lines;
use GD::Graph::colour;
my (@dates,@sales);
open(FILE,$ARGV[0]);
while(my $line = <FILE>)
{
chomp $line;
my ($d,$s) = split /:/,$line;
push @dates,$d;
push @sales,$s;
}
close(FILE);
my $my_graph = new GD::Graph::lines(600,480);
$my_graph->set_title_font(gdGiantFont,24);
$my_graph->set_x_label_font(gdGiantFont,14);
$my_graph->set_y_label_font(gdGiantFont,14);
$my_graph->set('x_label' => 'Date',
'y_label' => 'Sales',
'title' => 'Sales by date',
) or warn $my_graph->error;
open(FILE,">graph.png");
print FILE $my_graph->plot([\@dates,\@sales])->png;
close(FILE);
You can see a sample of the graph generated by the above script, and a simple data file (using colon separated dates and sales figures). You can see how simple and straightforward the process can be using GD::Graph. Most of the code is actually devoted to loading the data
and setting the fonts for the axis labels.