Graph(3pm) | User Contributed Perl Documentation | Graph(3pm) |
GD::Graph - Graph Plotting Module for Perl 5
use GD::Graph::moduleName;
GD::Graph is a perl5 module to create charts using the GD module. The following classes for graphs with axes are defined:
Additional types:
Distribution has no releases since 2007. It has new maintainer starting of 1.45 and my plan is to keep modules backwards compatible as much as possible, fix bugs with test cases, apply patches and release new versions to the CPAN.
I got repository from Martien without Benjamin's work, Benjamin couldn't find his repository, so everything else is imported from CPAN and BackPAN. Now it's all on github <https://github.com/ruz/GDGraph>. May be at some point Benjamin will find his VCS backup and we can restore full history.
Release 1.44_01 (development release) was released in 2007 by Benjamin, but never made into production version. This dev version contains very nice changes (truecolor, anti-aliasing and alpha support), but due to nature of how GD and GD::Graph works authors had to add third optional argument (truecolor) to all constructors in GD::Graph modules. I think that this should be and can be adjusted to receive named arguments in constructor and still be backwards compatible. If you were using that dev release and want to fast forward inclusion of this work into production release then contact ruz@cpan.org
Martien also has changes in his repository that were never published to CPAN. These are smaller and well isolated, so I can merge them faster.
My goal at this moment is to merge existing versions together, get rid of CVS reminders, do some repo cleanup, review existing tickets on rt.cpan.org. Join if you want to help.
See the samples directory in the distribution, and read the Makefile there.
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, hbars, lines, points, linespoints, mixed or pie).
my $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 ) or die $graph->error;
and plot the graph.
my $gd = $graph->plot(\@data) or die $graph->error;
Then do whatever your current version of GD allows you to do to save the file. For versions of GD older than 1.19 (or more recent than 2.15), 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 $graph->plot(\@data)->gif; print IMG $graph->plot(\@data)->png; print IMG $graph->plot(\@data)->gd; print IMG $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 = $graph->export_format; open(IMG, ">file.$format") or die $!; binmode IMG; print IMG $graph->plot(\@data)->$format(); close IMG;
or for CGI programs:
use CGI qw(:standard); #... my $format = $graph->export_format; print header("image/$format"); binmode STDOUT; print $graph->plot(\@data)->$format();
(the parentheses after $format are necessary, to help the compiler decide that you mean a method name there)
See under "SEE ALSO" for references to other documentation, especially the FAQ.
Note: as of the current version, this GD::Image object will always be palette-based, even if the installed version of GD supports true-color images.
Note also that if you draw on the GD::Image object before calling the plot method, you are responsible for making sure that the background colour is correct and for setting transparency.
Default: no logo.
Note: versions of GD higher than 2.0 (that is, since GIF support was restored after being removed owing to patent issues) do not support interlacing of GIF images. Support for interlaced PNG and progressive JPEG images remains available using this option.
All colours should have a valid value as described in "COLOURS", except boxclr, which can be undefined, in which case the box will not be filled.
All colours should have a valid value as described in "COLOURS".
$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) ]
options for bars, lines, points, linespoints, mixed and area charts.
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.
$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; } $graph->set( 'y_number_format' => \&y_format );
(Yes, I know this can be much shorter and more concise)
Default: undef.
For compatibility purposes, each of these will fall back on y_number_format if not specified.
Default: undef for both.
For example, when your X values are the months of the year (i.e. Jan - Dec), and you set x_label_skip to 3, the months printed on the axis will be Jan, Apr, Jul, Oct and Dec; even though Dec does not really belong to that sequence. If you do not like the last month to be printed, set x_last_label_skip to a true value.
This option has no effect in other circumstances. Also see x_tick_offset for another method to make this look better. Default: 0 for both
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 integer n in x_tick_offset + n * x_label_skip.
Also see x_last_label_skip for another method to influence this.
Note that if you use this option, that you need to use y1_label and y2_label, instead of just y_label, if you want the two axes to have different labels. The same goes for some other options starting with the letter 'y' and an underscore.
Default: 0.
Default: [1,2].
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.
By default 0 of the left axis is aligned with 0 of the right axis, it's not true if any of these options is defined.
Otherwise behaviour and default values are as with y_max_value and y_min_value.
NOTE that author of the feature implemented this for two_axes case only, patches are wellcome to expand over one y axis.
If two_axes is a true value, then y1_min_range and y2_min_range take precedence over y_min_range value.
Default: undef
Default: 8.
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.
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.
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.
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.
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.
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:
Default: undef
$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)
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
$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, 9: horizontal line, 10: vertical line. Note that the last two are not part of the default list.
Default: [1,2,3,4,5,6,7,8]
$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: lines
At the moment legend support is minimal.
Methods
If a key is undef or an empty string, the legend entry will be skipped.
Options
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.
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 GD::Graph::colour. "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.
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 GD::Text for more details and other things, since all font handling in GD::Graph is delegated to there.
Examples:
$graph->set_title_font('/fonts/arial.ttf', 18); $graph->set_legend_font(gdTinyFont); $graph->set_legend_font( ['verdana', 'arial', gdMediumBoldFont], 12)
(The above discussion is based on GD::Text 0.65. Older versions have more restrictive behaviour).
Note that this is an experimental feature, and its interface may, and likely will, change in the future. It currently does not work for area charts or pie charts.
A known problem with hotspots for GD::Graph::hbars is that the x and y coordinate come out transposed. This probably won't be fixed until the redesign of this section
GD::Graph keeps an internal set of coordinates for each data point and for certain features of a chart, like the title and axis labels. 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 for data point, and "get_feature_coordinates" for the chart features.
The <get_hotspot> 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], ... ],...
The "get_feature" method, when called with the name of a feature, returns a single array reference with a type and coordinates as described above. When called with no arguments, a hash reference is returned with the keys being all the currently defined and set features, and the values array references with the type and coordinates for each of those features.
GD::Graph objects inherit from the GD::Graph::Error class (not the other way around), so they behave in the same manner. The main feature of that behaviour is that you have the error() method available to get some information about what went wrong. The GD::Graph methods all return undef if something went wrong, so you should be able to write safe programs like this:
my $graph = GD::Graph->new() or die GD::Graph->error; $graph->set( %attributes ) or die $graph->error; $graph->plot($gdg_data) or die $graph->error;
More advanced usage is possible, and there are some caveats with this error handling, which are all explained in GD::Graph::Error.
Unfortunately, it is almost impossible to gracefully recover from an error in GD::Graph, so you really should get rid of the object, and recreate it from scratch if you want to recover. For example, to adjust the correct_width attribute if you get the error "Horizontal size too small" or "Vertical size too small" (in the case of hbar), you could do something like:
sub plot_graph { my $data = shift; my %attribs = @_; my $graph = GD::Graph::bars->new() or die GD::Graph->error; $graph->set(%attribs) or die $graph->error; $graph->plot($data) or die $graph->error; } my $gd; eval { $gd = plot_graph(\@data, %attribs) }; if ($@) { die $@ unless $@ =~ /size too small/; $gd = plot_graph(\@data, %attribs, correct_width => 0); }
Of course, you could also adjust the width this way, and you can check for other errors.
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.
GD::Graph objects cannot be reused. To create a new plot, you have to create a new GD::Graph object.
Rotated charts (ones with the X axis on the left) can currently only be created for bars. With a little work, this will work for all others as well. Please, be patient :)
Other outstanding bugs can (alas) probably be found in the RT queue for this distribution, at http://rt.cpan.org/Public/Dist/Display.html?Name=GDGraph
If you think you have found a bug, please check first to see if it has already been reported. If it has not, please do (you can use the web interface above or send e-mail to <bug-GDGraph@rt.cpan.org>). Bug reports should contain as many as possible of the following:
Of all of these, the third is probably the single most important, since producing a test case generally makes the explanation much more concise and understandable, as well as making it much simpler to show that the bug has been fixed. As an incidental benefit, if the bug is in fact caused by some code outside of GD::Graph, it will become apparent while you are writing the test case, thereby saving time and confusion for all concerned.
Martien Verbruggen <mgjv@tradingpost.com.au>
Current maintenance (including this release) by Benjamin Warfield <bwarfield@cpan.org>
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.
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, Ben Tilly, 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.
GD::Graph::FAQ, GD::Graph::Data, GD::Graph::Error, GD::Graph::colour
2022-07-24 | perl v5.34.0 |