Install and Use GD Graph to make charts in Perl

First you need to know if GD graph is installed on your machine or not. I am making these graphs in Linux, so here is how you can check and install GD Graph:

# apt-cache search perl | grep -i gd-graph
libgd-graph-perl - Graph Plotting Module for Perl 5
libgd-graph3d-perl - Create 3D Graphs with GD and GD::Graph

You need to install libgd-graph-perl thus do:

#apt-get install libgd-graph-perl

Now, after you are done with installation start making charts. Here are couple of examples:

A simple bar graph

5405355187 b1141f6348 m Install and Use GD Graph to make charts in Perl

#!/usr/bin/perl -w
use CGI qw/:standard/;
use GD::Graph::bars;

# Both the arrays should same number of entries.
my @data = (['Fall 01', 'Spr 01', 'Fall 02', 'Spr 02' ],
            [80, 90, 85, 75],
            [76, 55, 75, 95],
            [66, 58, 92, 83]);

my $mygraph = GD::Graph::bars->new(500, 300);
$mygraph->set(
    x_label     => 'Semester',
    y_label     => 'Marks',
    title       => 'Grade report for a student',
    # Draw bars with width 3 pixels
    bar_width   => 3,
    # Sepearte the bars with 4 pixels
    bar_spacing => 4,
    # Show the grid
    long_ticks  => 1,
    # Show values on top of each bar
    show_values => 1,
) or warn $mygraph->error;

$mygraph->set(logo_resize => 0.5);
$mygraph->set(logo_position => 'LR');

$mygraph->set_legend_font(GD::gdMediumBoldFont);
$mygraph->set_legend('Exam 1', 'Exam 2', 'Exam 3');
my $myimage = $mygraph->plot(\@data) or die $mygraph->error;

open(IMG, '>bars.png') or die $!;
binmode IMG;
print IMG $myimage->png;
close IMG;

Pie Chart

5405355181 e767ed6586 m Install and Use GD Graph to make charts in Perl

#!/usr/bin/perl -w
use CGI qw/:standard/;
use GD::Graph::pie;

@data = ([ qw( 1st 2nd 3rd 4th 5th 6th 7th ) ],
[ sort { $b < => $a} (5.6, 2.1, 3.03, 4.05, 1.34, 0.2, 2.56) ]
);

$my_graph = new GD::Graph::pie( 200, 200 );

$my_graph->set(
start_angle => 90,
'3d' => 0,
#if 1 then you will have 3d pie chart
label => 'Pie Chart',
# The following should prevent the 7th slice from getting a label
suppress_angle => 5,

transparent => 0,
);

my $myimage = $my_graph->plot(\@data) or die $my_graph->error;

open(IMG, '>pie.png') or die $!;
binmode IMG;
print IMG $myimage->png;
close IMG;

For more complex charts leave a comment here.

Tags: , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*