Recipe 15.18 Graphing Data

15.18.1 Problem

You have numerical data that you want to represent as a bar, pie, or line chart.

15.18.2 Solution

Use the GD::Graph::* modules from CPAN:

use GD::Graph::lines;                      # bars, lines, points, pie
$chart = GD::Graph::lines->new(480,320);
$chart->set(x_label => $X_AXIS_LABEL,      # no axes for pie chart
            y_label => $Y_AXIS_LABEL,
            title   => $GRAPH_TITLE,
            # ... more options possible
           );
$plot = $chart->plot($DATA_REF) or die $chart->error;
# do something with $plot->png which is the image in PNG form

Here is a sample data structure (every row must have the same number of values):

$DATA_REF = [
              [ 1990, 1992, 1993, 1995, 2002 ],      # X values
              [ 10,   15,   18,   20,   25   ],      # first dataset
              [ 9,    undef,17,   undef,12   ],      # second dataset
              # ...
            ];

15.18.3 Discussion

The GD::Graph module requires you to have the GD module installed, which itself depends on a C library available from http://www.boutell.com/gd/. Early versions of this library created GIF images, but since the owners of the GIF patent are cracking down, the library now emits PNG and JPEG images:

$png_data = $plot->png;
$jpg_data = $plot->jpeg;

The documentation for GD::Graph lists a large number of options you can fine-tune (colors, fonts, placement), but the most important ones are labels and the image title. There are no axes to label in pie charts, so the x_label and y_label options are not available. By default, pie charts are drawn with a pseudo-3D look, which you can disable by setting the 3d option to a false value.

Recipe 15.23 contains a program that (crudely) extracts the day of the week on which each mail message in a mailbox was sent, and then graphs that data.

15.18.4 See Also

Documentation for the GD and GD::Graph modules; Perl Graphics Programming, by Shawn Wallace (O'Reilly)