Last week I was looking for way to get a time-scale on my charts created with GD::Graph::bars.
I got some very useful hints re. using loops/dates (
and the support from the Data-Table author). Without these hints I wouldn't have been able to get the following result. It works, maybe it's sloppy code?. Without doubt it can be improved. Hope any of you see use in me posting this. Comments, always welcome.
#!/usr/bin/perl -w
use strict;
use diagnostics;
use Data::Table;
use GD::Graph::bars;
use Date::Manip;
open( OUT, ">table.html" ) or die "cant open out $!";
# Creating first table with present data
my $table =
new Data::Table(
[ [ 20070410, 20070415, 20070417, 20070420 ], [ 10, 20, 15, 42 ] ]
+,
[ 'Dates', 'Values' ], 1 );
print OUT $table->html;
print OUT
"<img src=\"graph.png\" width=\"700\" height=\"150\" alt=\"graph\" ali
+gn=\"right\">";
my $value_start = $table->elm( 0, 0 );
my $value_end = $table->elm( $table->nofRow - 1, 0 );
my $start = UnixDate( $value_start, '%m/%d/%Y' ); # No
+v 22, 1999
my $end = UnixDate( $value_end, '%m/%d/%Y' ); # mm/
+dd/yyyy
my @dates = ParseRecur( "0:0:0:1:0:0:0", $start, $start, $end );
foreach my $x (@dates) {
$x = UnixDate( $x, '%Y%m%d' );
}
my $nums = @dates;
my @second_column = undef;
my $x = undef;
for ( my $var = 0 ; $var < $nums - 1 ; $var++ ) {
push( @second_column, 0 );
}
# Creating second table with missing calendar dates
my $table_cal =
new Data::Table( [ \@dates, \@second_column ], [ 'Dates', 'Values' ]
+, 1 );
print OUT $table_cal->html;
$table->rowMerge($table_cal); # Merging two tables
$table->sort( "Dates", 0, 0 ); # Sort by col 'Dates',numerical,ascen
+ding
# grouping rows by Dates and adding Values.
$table = $table->group( ["Dates"], ["Values"], [ \&adding ], ["Values"
+] );
print OUT $table->html;
for my $graph ( GD::Graph::bars->new( 700, 150 ) ) {
$graph->set(
'y_number_format' => '%d',
transparent => 0,
values_vertical => 1,
show_values => 1,
);
$graph->set( 'x_labels_vertical' => 1 );
my $gd = $graph->plot( $table->colRefs( [ 0, 1 ] ) );
open( IMG, ">graph.png" ) or die $!;
binmode IMG;
print IMG $gd->png;
close IMG;
}
sub adding {
my @data = @_;
my $sum = 0;
my $x = 0;
foreach $x (@data) {
next unless $x;
$sum += $x;
}
return $sum;
}