NAME GD::Graph - Graph Plotting Module for Perl 5 SYNOPSIS use GD::Graph::moduleName; DESCRIPTION GD::Graph is a *perl5* module to create charts using the GD module. The following classes for graphs with axes are defined: `GD::Graph::lines' Create a line chart. `GD::Graph::bars' Create a bar chart. `GD::Graph::points' Create an chart, displaying the data as points. `GD::Graph::linespoints' Combination of lines and points. `GD::Graph::area' Create a graph, representing the data as areas under a line. `GD::Graph::mixed' Create a mixed type graph, any combination of the above. At the moment this is fairly limited. Some of the options that can be used with some of the individual graph types won't work very well. Multiple bar graphs in a mixed graph won't display very nicely. Additional types: `GD::Graph::pie' Create a pie chart. EXAMPLES See the samples directory in the distribution, and read the Makefile there. USAGE Fill an array of arrays with the x values and the values of the data sets. Make sure that every array is the same size, otherwise *GD::Graph* will complain and refuse to compile the graph. @data = ( ["1st","2nd","3rd","4th","5th","6th","7th", "8th", "9th"], [ 1, 2, 5, 6, 3, 1.5, 1, 3, 4], [ sort { $a <=> $b } (1, 2, 5, 6, 3, 1.5, 1, 3, 4) ] ); If you don't have a value for a point in a certain dataset, you can use undef, and the point will be skipped. Create a new *GD::Graph* object by calling the *new* method on the graph type you want to create (*chart* is *bars*, *lines*, *points*, *linespoints*, *mixed* or *pie*). $graph = GD::Graph::chart->new(400, 300); Set the graph options. $graph->set( x_label => 'X Label', y_label => 'Y label', title => 'Some simple graph', y_max_value => 8, y_tick_number => 8, y_label_skip => 2 ); and plot the graph. my $gd = $my_graph->plot(\@data); Then do whatever your current version of GD allows you to do to save the file. For versions of GD older than 1.19, you'd do something like: open(IMG, '>file.gif') or die $!; binmode IMG; print IMG $gd->gif; close IMG; and for newer versions (1.20 and up) you'd write open(IMG, '>file.png') or die $!; binmode IMG; print IMG $gd->png; or open(IMG, '>file.gd2') or die $!; binmode IMG; print IMG $gd->gd2; Then there's also of course the possibility of using a shorter version (for each of the export functions that GD supports): print IMG $my_graph->plot(\@data)->gif; print IMG $my_graph->plot(\@data)->png; print IMG $my_graph->plot(\@data)->gd; print IMG $my_graph->plot(\@data)->gd2; If you want to write something that doesn't require your code to 'know' whether to use gif or png, you could do something like: if ($gd->can('png')) { # blabla } or you can use the convenience method `export_format': my $format = $my_graph->export_format; open(IMG, ">file.$format") or die $!; binmode IMG; print IMG $my_graph->plot(\@data)->$format(); close IMG; or for CGI scripts: use CGI qw(:standard); #... my $format = $my_graph->export_format; print header("image/$format"); binmode STDOUT; print $my_graph->plot(\@data)->$format(); (the parentheses after $format are necessary, to help the compiler decide that you mean a method name there) METHODS Methods for all graphs GD::Graph::chart->new([width,height]) Create a new object $graph with optional width and heigth. Default width = 400, default height = 300. *chart* is either *bars*, *lines*, *points*, *linespoints*, *area*, *mixed* or *pie*. $graph->set_text_clr(*colour name*) Set the colour of the text. This will set the colour of the titles, labels, and axis labels to *colour name*. Also see the options *textclr*, *labelclr* and *axislabelclr*. $graph->set_title_font(font specification) Set the font that will be used for the title of the chart. See the section on "FONTS". $graph->plot(*\@data*) Plot the chart, and return the GD::Image object. $graph->set(attrib1 => value1, attrib2 => value2 ...) Set chart options. See OPTIONS section. $graph->get(attrib1, attrib2) Returns a list of the values of the attributes. In scalar context returns the value of the first attribute only. $graph->gd() Get the GD::Image object that is going to be used to draw on. You can do this either before or after calling the plot method, to do your own drawing. Note that if you draw on the GD::Image object before calling the plot method that you are responsible for making sure that the background colour is correct and for setting transparency. $graph->export_format() Query the export format of the GD library in use. In scalar context, it returns 'gif', 'png' or undefined, which is sufficient for most people's use. In a list context, it returns a list of all the formats that are supported by the current version of GD. It can be called as a class or object method $graph->can_do_ttf() Returns true if the current GD library supports TrueType fonts, False otherwise. Can also be called as a class method or static method. Methods for Pie charts $graph->set_label_font(font specification) $graph->set_value_font(font specification) Set the font that will be used for the label of the pie or the values on the pie. See the section on "FONTS". Methods for charts with axes. $graph->set_x_label_font(font specification) $graph->set_y_label_font(font specification) $graph->set_x_axis_font(font specification) $graph->set_y_axis_font(font specification) $graph->set_values_font(font specification) Set the font for the x and y axis label, the x and y axis value labels, and for the values printed above the data points. See the section on "FONTS". $graph->get_hotspot($dataset, $point) Experimental: Return a coordinate specification for a point in a dataset. Returns a list. If the point is not specified, returns a list of array references for all points in the dataset. If the dataset is also not specified, returns a list of array references for each data set. See the section on "HOTSPOTS". OPTIONS Options for all graphs width, height The width and height of the canvas in pixels Default: 400 x 300. NB At the moment, these are read-only options. If you want to set the size of a graph, you will have to do that with the *new* method. t_margin, b_margin, l_margin, r_margin Top, bottom, left and right margin of the canvas. These margins will be left blank. Default: 0 for all. logo Name of a logo file. Generally, this should be the same format as your version of GD exports images in. At the moment there is no support for reading gd format files or xpm files. Default: no logo. logo_resize, logo_position Factor to resize the logo by, and the position on the canvas of the logo. Possible values for logo_position are 'LL', 'LR', 'UL', and 'UR'. (lower and upper left and right). Default: 'LR'. transparent If set to a true value, the produced image will have the background colour marked as transparent (see also option *bgclr*). Default: 1. interlaced If set to a true value, the produced image will be interlaced. Default: 1. Colours bgclr, fgclr, boxclr, accentclr, shadowclr Drawing colours used for the chart: background, foreground (axes and grid), axis box fill colour, accents (bar, area and pie outlines), and shadow (currently only for bars). All colours should have a valid value as described in the section on "COLOURS", except boxclr, which can be undefined, in which case the box will not be filled. shadow_depth Depth of a shadow, positive for right/down shadow, negative for left/up shadow, 0 for no shadow (default). Also see the `shadowclr' and `bar_spacing' options. labelclr, axislabelclr, legendclr, valuesclr, textclr Text Colours used for the chart: label (labels for the axes or pie), axis label (misnomer: values printed along the axes, or on a pie slice), legend text, shown values text, and all other text. All colours should have a valid value as described in the section on "COLOURS". dclrs (short for datacolours) This controls the colours for the bars, lines, markers, or pie slices. This should be a reference to an array of colour names as defined in the GD::Graph::colour manpage (`perldoc GD::Graph::colour' for the names available). $graph->set( dclrs => [ qw(green pink blue cyan) ] ); The first (fifth, ninth) data set will be green, the next pink, etc. A colour can be `undef', in which case the data set will not be drawn. This can be useful for cumulative bar sets where you want certain data series (often the first one) not to show up, which can be used to emulate error bars (see examples 1-7 and 6-3 in the distribution). Default: [ qw(lred lgreen lblue lyellow lpurple cyan lorange) ] borderclrs This controls the colours of the borders of the bars data sets. Like dclrs, it is a reference to an array of colour names as defined in the GD::Graph::colour manpage. Setting a border colour to `undef' means the border will not be drawn. cycle_clrs If set to a true value, bars will not have a colour from `dclrs' per dataset, but per point. The colour sequence will be identical for each dataset. Note that this may have a weird effect if you are drawing more than one data set. If this is set to a value larger than 1 the border colour of the bars will cycle through the colours in `borderclrs'. accent_treshold Not really a colour, but it does control a visual aspect: Accents on bars are only drawn when the width of a bar is larger than this number of pixels. Accents inside areas are only drawn when the horizontal distance between points is larger than this number. Default 4 Options for graphs with axes. options for *bars*, *lines*, *points*, *linespoints*, *mixed* and *area* charts. long_ticks, tick_length If *long_ticks* is a true value, ticks will be drawn the same length as the axes. Otherwise ticks will be drawn with length *tick_length*. if *tick_length* is negative, the ticks will be drawn outside the axes. Default: long_ticks = 0, tick_length = 4. These attributes can also be set for x and y axes separately with x_long_ticks, y_long_ticks, x_tick_length and y_tick_length. x_ticks If *x_ticks* is a true value, ticks will be drawm for the x axis. These ticks are subject to the values of *long_ticks* and *tick_length*. Default: 1. y_tick_number Number of ticks to print for the Y axis. Use this, together with *y_label_skip* to control the look of ticks on the y axis. Default: 5. y_number_format This can be either a string, or a reference to a subroutine. If it is a string, it will be taken to be the first argument to an sprintf, with the value as the second argument: $label = sprintf( $s->{y_number_format, $value ); If it is a code reference, it will be executed with the value as the argument: $label = &{$s->{y_number_format}}($value); This can be useful, for example, if you want to reformat your values in currency, with the - sign in the right spot. Something like: sub y_format { my $value = shift; my $ret; if ($value >= 0) { $ret = sprintf("\$%d", $value * $refit); } else { $ret = sprintf("-\$%d", abs($value) * $refit); } return $ret; } $my_graph->set( 'y_number_format' => \&y_format ); (Yes, I know this can be much shorter and more concise) Default: undef. x_label_skip, y_label_skip Print every *x_label_skip*th number under the tick on the x axis, and every *y_label_skip*th number next to the tick on the y axis. Default: 1 for both. x_tick_offset When x_label_skip is used, this will skip the first x_tick_offset values in the labels before starting to print. Let me give an example. If you have a series of X labels like qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec) and you set x_label_skip to 3, you will see ticks on the X axis for Jan, Apr, Jul, Oct and Dec. This is not always what is wanted. If you set x_tick_offset to 1, you get Feb, May, Aug, Nov and Dec, and if you set it to 2, you get Mar, Jun Sep and Dec, and this last one definitely looks better. A combination of 6 and 5 also works nice for months. Note that the value for x_tick_offset is periodical. This means that it will have the same effect for each nteger n in x_tick_offset + n * x_label_skip. x_all_ticks Force a print of all the x ticks, even if x_label_skip is set to a value Default: 0. x_label_position Controls the position of the X axis label (title). The value for this should be between 0 and 1, where 0 means aligned to the left, 1 means aligned to the right, and 1/2 means centered. Default: 3/4 y_label_position Controls the position of both Y axis labels (titles). The value for this should be between 0 and 1, where 0 means aligned to the bottom, 1 means aligned to the top, and 1/2 means centered. Default: 1/2 x_labels_vertical If set to a true value, the X axis labels will be printed vertically. This can be handy in case these labels get very long. Default: 0. x_plot_values, y_plot_values If set to a true value, the values of the ticks on the x or y axes will be plotted next to the tick. Also see *x_label_skip, y_label_skip*. Default: 1 for both. box_axis Draw the axes as a box, if true. Default: 1. two_axes Use two separate axes for the first and second data set. The first data set will be set against the left axis, the second against the right axis. If this is set to a true value, trying to use anything else than 2 datasets will generate an error. Default: 0. zero_axis If set to a true value, the axis for y values of 0 will always be drawn. This might be useful in case your graph contains negative values, but you want it to be clear where the zero value is. (see also *zero_axis_only* and *box_axes*). Default: 0. zero_axis_only If set to a true value, the zero axis will be drawn (see *zero_axis*), and no axis at the bottom of the graph will be drawn. The labels for X values will be placed on the zero exis. Default: 0. y_max_value, y_min_value Maximum and minimum value displayed on the y axis. If two_axes is a true value, then y1_min_value, y1_max_value (for the left axis), and y2_min_value, y2_max_value (for the right axis) take precedence over these. The range (y_min_value..y_max_value) has to include all the values of the data points, or *GD::Graph* will die with a message. For bar and area graphs, the range (y_min_value..y_max_value) has to include 0. If it doesn't, the values will be adapted before attempting to draw the graph. Default: Computed from data sets. axis_space This space will be left blank between the axes and the tick value text. Default: 4. text_space This space will be left open between text elements and the graph (text elements are title and axis labels. Default: 8. cumulate If this attribute is set to a true value, the data sets will be cumulated. This means that they will be stacked on top of each other. A side effect of this is that `overwrite' will be set to a true value. Notes: This only works for bar and area charts at the moment. If you have negative values in your data sets, setting this option might produce odd results. Of course, the graph itself would be quite meaningless. overwrite If set to 0, bars of different data sets will be drawn next to each other. If set to 1, they will be drawn in front of each other. Default: 0. Note: Setting overwrite to 2 to produce cumulative sets is deprecated, and may disappear in future versions of GD::Graph. Instead see the `cumulate' attribute. correct_width If this is set to a true value and `x_tick_number' is false, then the width of the graph will be recalculated to make sure that each data point is exactly an integer number of pixels wide. You probably never want to fiddle with this. When this value is true, you will need to make sure that the number of data points is smaller than the number of pixels in the plotting area of the chart. If you get errors saying that your horizontal size if too small, you may need to manually switch this off, or consider using something else than a bar type for your chart. Default: 1 for bar, calculated at runtime for mixed charts, 0 for others. Plotting data point values with the data point Sometimes you will want to plot the value of a data point or bar above the data point for clarity. GD::Graph allows you to control this in a generic manner, or even down to the single point. show_values Set this to 1 to display the value of each data point above the point or bar itself. No effort is being made to ensure that there is enough space for the text. Set this to a GD::Graph::Data object, or an array reference of the same shape, with the same dimensions as your data object that you pass in to the plot method. The reason for this option is that it allows you to make a copy of your data set, and selectively set points to `undef' to disable plotting of them. my $data = GD::Graph::Data->new( [ [ 'A', 'B', 'C' ], [ 1, 2, 3 ], [ 11, 12, 13 ] ]); my $values = $data->copy; $values->set_y(1, 1, undef); $values->set_y(2, 0, undef); $graph->set(show_values => $values); $graph->plot($data); Default: 0. values_vertical If set to a true value, the values will be printed vertically, instead of horizontally. This can be handy if the values are long numbers. Default: 0. values_space Space to insert between the data point and the value to print. Default: 4. values_format How to format the values for display. See y_number_format for more information. Default: undef. Options for graphs with a numerical X axis First of all: GD::Graph does not support numerical x axis the way it should. Data for X axes should be equally spaced. That understood: There is some support to make the printing of graphs with numerical X axis values a bit better, thanks to Scott Prahl. If the option `x_tick_number' is set to a defined value, GD::Graph will attempt to treat the X data as numerical. Extra options are: x_tick_number If set to *'auto'*, GD::Graph will attempt to format the X axis in a nice way, based on the actual X values. If set to a number, that's the number of ticks you will get. If set to undef, GD::Graph will treat X data as labels. Default: undef. x_min_value, x_max_value The minimum and maximum value to use for the X axis. Default: computed. x_number_format See y_number_format x_label_skip See y_label_skip Options for graphs with bars bar_width The width of a bar in pixels. Also see `bar_spacing'. Use `bar_width' If you want to have fixed-width bars, no matter how wide the chart gets. Default: as wide as possible, within the constraints of the chart size and `bar_spacing' setting. bar_spacing Number of pixels to leave open between bars. This works well in most cases, but on some platforms, a value of 1 will be rounded off to 0. Use `bar_spacing' to get a fixed amount of space between bars, with variable bar widths, depending on the width of the chart. Note that if `bar_width' is also set, this setting will be ignored, and automatically calculated. Default: 0 Options for graphs with lines line_types Which line types to use for *lines* and *linespoints* graphs. This should be a reference to an array of numbers: $graph->set( line_types => [3, 2, 4] ); Available line types are 1: solid, 2: dashed, 3: dotted, 4: dot-dashed. Default: [1] (always use solid) line_type_scale Controls the length of the dashes in the line types. default: 6. line_width The width of the line used in *lines* and *linespoints* graphs, in pixels. Default: 1. skip_undef For all other axes graph types, the default behaviour is (by their nature) to not draw a point when the Y value is `undef'. For line charts the point gets skipped as well, but the line is drawn between the points n-1 to n+1 directly. If `skip_undef' has a true value, there will be a gap in the chart where a Y value is undefined. Note that a line will not be drawn unless there are *at least two* consecutive data points exist that have a defined value. The following data set will only plot a very short line towards the end if `skip_undef' is set: @data = ( [ qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct ) ], [ 1, undef, 2, undef, 3, undef, 4, undef, 5, 6 ] ); This option is useful when you have a consecutive gap in your data, or with linespoints charts. If you have data where you have intermittent gaps, be careful when you use this. Default value: 0 Options for graphs with points markers This controls the order of markers in *points* and *linespoints* graphs. This should be a reference to an array of numbers: $graph->set( markers => [3, 5, 6] ); Available markers are: 1: filled square, 2: open square, 3: horizontal cross, 4: diagonal cross, 5: filled diamond, 6: open diamond, 7: filled circle, 8: open circle. Default: [1,2,3,4,5,6,7,8] marker_size The size of the markers used in *points* and *linespoints* graphs, in pixels. Default: 4. Options for mixed graphs types A reference to an array with graph types, in the same order as the data sets. Possible values are: $graph->set( types => [qw(lines bars points area linespoints)] ); $graph->set( types => ['lines', undef, undef, 'bars'] ); values that are undefined or unknown will be set to `default_type'. Default: all set to `default_type' default_type The type of graph to draw for data sets that either have no type set, or that have an unknown type set. Default: lines Graph legends (axestype graphs only) At the moment legend support is minimal. Methods $graph->set_legend(*@legend_keys*); Sets the keys for the legend. The elements of @legend_keys correspond to the data sets as provided to *plot()*. If a key is *undef* or an empty string, the legend entry will be skipped. $graph->set_legend_font(*font name*); Sets the font for the legend text (see the section on "FONTS"). Default: GD::gdTinyFont. Options legend_placement Where to put the legend. This should be a two letter key of the form: 'B[LCR]|R[TCB]'. The first letter indicates the placement (*B*ottom or *R*ight), and the second letter the alignment (*L*eft, *R*ight, *C*enter, *T*op, or *B*ottom). Default: 'BC' If the legend is placed at the bottom, some calculations will be made to ensure that there is some 'intelligent' wrapping going on. if the legend is placed at the right, all entries will be placed below each other. legend_spacing The number of pixels to place around a legend item, and between a legend 'marker' and the text. Default: 4 legend_marker_width, legend_marker_height The width and height of a legend 'marker' in pixels. Defaults: 12, 8 lg_cols If you, for some reason, need to force the legend at the bottom to have a specific number of columns, you can use this. Default: computed Options for pie graphs 3d If set to a true value, the pie chart will be drawn with a 3d look. Default: 1. pie_height The thickness of the pie when *3d* is true. Default: 0.1 x height. start_angle The angle at which the first data slice will be displayed, with 0 degrees being "6 o'clock". Default: 0. suppress_angle If a pie slice is smaller than this angle (in degrees), a label will not be drawn on it. Default: 0. label Print this label below the pie. Default: undef. COLOURS All references to colours in the options for this module have been shortened to clr. The main reason for this was that I didn't want to support two spellings for the same word ('colour' and 'color') Wherever a colour is required, a colour name should be used from the package the GD::Graph::colour manpage. `perldoc GD::Graph::colour' should give you the documentation for that module, containing all valid colour names. I will probably change this to read the systems rgb.txt file if it is available. FONTS Depending on your version of GD, this accepts both GD builtin fonts or the name of a TrueType font file. In the case of a TrueType font, you must specify the font size. See the GD::Text manpage for more details and other things, since all font handling in GD::Graph is delegated to there. Examples: $my_graph->set_title_font('/fonts/arial.ttf', 18); $my_graph->set_legend_font(gdTinyFont); $my_graph->set_legend_font( ['verdana', 'arial', gdMediumBoldFont], 12) (The above discussion is based on GD::Text 0.65. Older versions have more restrictive behaviour). HOTSPOTS *Note that this is an experimental feature, and its interface may, and likely will, change in the future* GD::Graph keeps an internal set of coordinates for each data point. This specification is very similar to the HTML image map specification, and in fact exists mainly for that purpose. You can get at these hotspots with the `get_hotspot' method. This method accepts two optional arguments, the number of the dataset you're interested in, and the number of the point in that dataset you're interested in. When called with two arguments, the method returns a list of one of the following forms: 'rect', x1, y1, x2, y2 'poly', x1, y1, x2, y2, x3, y3, .... 'line', xs, ys, xe, ye, width The parameters for `rect' are the coordinates of the corners of the rectangle, the parameters for `poly' are the coordinates of the vertices of the polygon, and the parameters for the `line' are the coordinates for the start and end point, and the line width. It should be possible to almost directly translate these lists into HTML image map specifications. If the second argument to `get_hotspot' is omitted, a list of references to arrays will be returned. This list represents all the points in the dataset specified, and each array referred to is of the form outlined above. ['rect', x1, y1, x2, y2 ], ['rect', x1, y1, x2, y2], ... if both arguments to `get_hotspot' are omitted, the list that comes back will contain references to arrays for each data set, which in turn contain references to arrays for each point. [ ['rect', x1, y1, x2, y2 ], ['rect', x1, y1, x2, y2], ... ], [ ['line', xs, ys, xe, ye, w], ['line', xs, ys, xe, ye, w], ... ],... NOTES As with all Modules for Perl: Please stick to using the interface. If you try to fiddle too much with knowledge of the internals of this module, you could get burned. I may change them at any time. BUGS GD::Graph objects cannot be reused. To create a new plot, you have to create a new GD::Graph object. AUTHOR Martien Verbruggen Copyright GIFgraph: Copyright (c) 1995-1999 Martien Verbruggen. Chart::PNGgraph: Copyright (c) 1999 Steve Bonds. GD::Graph: Copyright (c) 1999 Martien Verbruggen. All rights reserved. This package is free software; you can redistribute it and/or modify it under the same terms as Perl itself. Acknowledgements Thanks to Steve Bonds for releasing Chart::PNGgraph, and keeping the code alive when GD reached version 1.20, and I didn't have time to do something about it. Thanks to the following people for contributing code, or sending me fixes: Dave Belcher, Steve Bonds, Mike Bremford, Damon Brodie, Gary Deschaines brian d foy, Edwin Hildebrand, Ari Jolma, Tim Meadowcroft, Honza Pazdziora, Scott Prahl, Vegard Vesterheim, Jeremy Wadsack. And some people whose real name I don't know, and whose email address I'd rather not publicise without their consent. SEE ALSO the GD::Graph::FAQ manpage, the GD::Graph::Data manpage, the GD::Graph::Error manpage, the GD::Graph::colour manpage