Graph(3)
πΈ NAME πΈ
GD::Graph is the Graph Plotting Module for Perl 5 β this is the Graph(3) manual page, bestie, and yeah it's the user-contributed Perl documentation vibe. π
β¨ SYNOPSIS β¨
use GD::Graph::moduleName;
π¦ DESCRIPTION π¦
Okay so GD::Graph is a perl5 module that makes charts using the GD module. Here are the classes for graphs with axes, and they are literally all defined:
GD::Graph::linesβ makes a line chart. iconic.GD::Graph::barsandGD::Graph::hbarsβ make a bar chart with vertical or horizontal bars.GD::Graph::pointsβ makes a chart that displays the data as points.GD::Graph::linespointsβ the combo of lines and points. main character energy.GD::Graph::areaβ makes a graph that represents the data as areas under a line.GD::Graph::mixedβ makes 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. Bar graphs drawn after lines or points graphs may obscure the earlier data, and specifyingbar_widthwill not produce the results you probably expected. π- Additional types:
GD::Graph::pieβ makes a pie chart. cute.
π« DISTRIBUTION STATUS π«
π 2023 Update π
This new release fixes some tests that started to fail based on changes in dependencies. We hope this gets all tests passing again so users can install cleanly.
The new active repo is here: https://github.com/bestpractical/gdgraph.
You can continue to use https://rt.cpan.org for bug reports.
π Status from 2013 π
Distribution has no releases since 2007. It has a new maintainer starting of 1.45, and the 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.
The repository got got from Martien without Benjamin's work β Benjamin couldn't find his repository β so everything else was imported from CPAN and BackPAN. Now it's all on github at 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. The thinking is 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 they can be merged faster.
The 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. π«Ά
π EXAMPLES π
Peep 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. lowkey useful.
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 β not just cute decoration, bestie)
See under SEE ALSO for references to other documentation, especially the FAQ.
π METHODS π
π§ Methods for all graphs π§
GD::Graph::chart->new([width,height])β create a new object$graphwith optional width and height. Default width =400, default height =300. chart is eitherbars,lines,points,linespoints,area,mixedorpie.$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 optionstextclr,labelclrandaxislabelclr.$graph->set_title_font(font specification)β set the font that will be used for the title of the chart. See FONTS.$graph->plot(\@data)β plot the chart, and return theGD::Imageobject.$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 theGD::Imageobject that is going to be used to draw on. You can do this either before or after calling theplotmethod, to do your own drawing.
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 theGD::Imageobject before calling theplotmethod, you are responsible for making sure that the background colour is correct and for setting transparency. no pressure lol
$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)and$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 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), and$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 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 HOTSPOTS.$graph->get_feature_coordinates($feature_name)β Experimental: return a coordinate specification for a certain feature in the chart. Currently, features that are defined areaxes, the coordinates of the rectangle within the axes;x_label,y1_labelandy2_label, the labels printed along the axes, withy_labelprovided as an alias fory1_label; andtitlewhich is the title text box. See HOTSPOTS.
π OPTIONS π
πΈ Options for all graphs πΈ
width,heightβ the width and height of the canvas in pixels. Default:400x300.
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. periodt.
t_margin,b_margin,l_margin,r_marginβ top, bottom, left and right margin of the canvas. These margins will be left blank. Default:0for all.logoβ name of a logo file. Generally, this should be the same format as your version of GD exports images in. Currently, this file may be in any format that GD can import, but please see GD if you use an XPM file and get unexpected results.
Default: no logo.
logo_resize,logo_positionβ factor to resize the logo by, and the position on the canvas of the logo. Possible values forlogo_positionare'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 optionbgclr). Default:1.interlacedβ if set to a true value, the produced image will be interlaced. Default:1.
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. π
π¨ Colours π¨
Okay bestie, this whole cluster is the palette situation π . Every colour value here needs to be valid like the COLOURS section says, unless we specifically call out an exception. π«Ά
bgclr,fgclr,boxclr,accentclr,shadowclrβ the 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 COLOURS, exceptboxclr, which can be undefined β in which case the box will not be filled. β¨shadow_depthβ depth of a shadow. Positive means right/down shadow, negative means left/up shadow, and0means no shadow (that's the default). Also see theshadowclrandbar_spacingoptions. πΈ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 COLOURS. πdclrs(short for datacolours) β this controls the colours for the bars, lines, markers, or pie slices. It should be a reference to an array of colour names as defined inGD::Graph::colour(perldoc GD::Graph::colourfor 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. Likedclrs, it is a reference to an array of colour names as defined inGD::Graph::colour. 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 fromdclrsper 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 than1, the border colour of the bars will cycle through the colours inborderclrs. π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. Default4. π₯
π Options for graphs with axes π
These are the options for bars, lines, points, linespoints, mixed and area charts. π¦
x_label,y_labelβ the labels to be printed next to, or just below, the axes. Note that if you use thetwo_axesoption that you need to usey1_labelandy2_label. πlong_ticks,tick_lengthβ iflong_ticksis a true value, ticks will be drawn the same length as the axes. Otherwise ticks will be drawn with lengthtick_length. Iftick_lengthis 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 withx_long_ticks,y_long_ticks,x_tick_lengthandy_tick_length. β¨x_ticksβ ifx_ticksis a true value, ticks will be drawn for the x axis. These ticks are subject to the values oflong_ticksandtick_length. Default:1. π―y_tick_numberβ number of ticks to print for the Y axis. Use this, together withy_label_skipto 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 asprintf, 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;
}
$graph->set( 'y_number_format' => \&y_format );
(Yes, I know this can be much shorter and more concise) Default: undef. π
y1_number_format,y2_number_formatβ as withy_number_format, these can be either a string, or a reference to a subroutine. These are used as formats for graphs with two y-axis scales so that independent formats can be used. For compatibility purposes, each of these will fall back ony_number_formatif not specified. Default:undeffor both. π«Άx_label_skip,y_label_skipβ print everyx_label_skipth number under the tick on the x axis, and everyy_label_skipth number next to the tick on the y axis. Default:1for both. πx_last_label_skipβ by default, whenx_label_skipis set to something higher than1, the last label on the axis will be printed, even when it doesn't belong to the normal series that should be printed. Setting this to a true value prevents that. For example, when your X values are the months of the year (i.e. Jan - Dec), and you setx_label_skipto3, 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, setx_last_label_skipto a true value. This option has no effect in other circumstances. Also seex_tick_offsetfor another method to make this look better. Default:0for both. πΈx_tick_offsetβ whenx_label_skipis used, this will skip the firstx_tick_offsetvalues in the labels before starting to print. Let me give you 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 integer n in x_tick_offset + n * x_label_skip. Also see x_last_label_skip for another method to influence this. π¦
x_all_ticksβ force a print of all the x ticks, even ifx_label_skipis set to a value. Default:0. π₯x_label_positionβ controls the position of the X axis label (title). The value for this should be between0and1, where0means aligned to the left,1means aligned to the right, and1/2means centered. Default:3/4. βy_label_positionβ controls the position of both Y axis labels (titles). The value for this should be between0and1, where0means aligned to the bottom,1means aligned to the top, and1/2means 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 seex_label_skip,y_label_skip. Default:1for both. πbox_axisβ draw the axes as a box, if true. Default:1. πno_axesβ draw no axes at all. If this is set toundef, all axes are drawn. If it is set to0, the zero axis will be drawn, for bar charts only. If this is set to a true value, no axes will be drawn at all. Value labels on the axes and ticks will also not be drawn, but axis lables are drawn. Default:undef. π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 more than two data sets are being plotted, theuse_axisoption should be used to specify which data sets use which axis. Note that if you use this option, that you need to usey1_labelandy2_label, instead of justy_label, if you want the two axes to have different labels. The same goes for some other options starting with the letteryand an underscore. Default:0. πuse_axisβ if two y-axes are in use and more than two datasets are specified, set this option to an array reference containing a value of1or2(for the left and right scales respectively) for each dataset being plotted. That is, to plot three datasets with the second on a different scale than the first and third, set this to"[1,2,1]". Default:[1,2]. π§zero_axisβ if set to a true value, the axis for y values of0will 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 alsozero_axis_onlyandbox_axes). Default:0. πzero_axis_onlyβ if set to a true value, the zero axis will be drawn (seezero_axis), and no axis at the bottom of the graph will be drawn. The labels for X values will be placed on the zero axis. Default:0. πy_max_value,y_min_valueβ maximum and minimum value displayed on the y axis. The range (y_min_value..y_max_value) has to include all the values of the data points, orGD::Graphwill die with a message. For bar and area graphs, the range (y_min_value..y_max_value) has to include0. If it doesn't, the values will be adapted before attempting to draw the graph. Default: Computed from data sets. π¨y1_max_value,y1_min_value,y2_max_value,y2_min_valueβ maximum and minimum values for left (y1) and right (y2) axes whentwo_axesis a true value. Take precedence overy_min_valueandy_max_value. By default0of the left axis is aligned with0of the right axis, it's not true if any of these options is defined. Otherwise behaviour and default values are as withy_max_valueandy_min_value. πy_min_range,y1_min_range,y2_min_rangeβ okay so these set the minimal range between min and max values on the y axis, and that range is used to adjust the computedy_min_valueandy_max_value.
NOTE that the author of the feature implemented this for the two_axes case only, and patches are wellcome to expand over one y axis. (their spelling, not mine π)
If two_axes is a true value, then y1_min_range and y2_min_range take precedence over the y_min_range value.
Default: undef.
axis_spaceβ this space gets left blank between the axes and the tick value text. Default:4.text_spaceβ this space gets 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 get cumulated, meaning they're stacked on top of each other. Side effect:overwritegets 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 to0, bars of different data sets will be drawn next to each other. If set to1, they will be drawn in front of each other. Default:0.
Note: settingoverwriteto2to produce cumulative sets is deprecated, and may disappear in future versions ofGD::Graph. Instead see thecumulateattribute.
correct_widthβ if this is set to a true value andx_tick_numberis false, then the width of the graph (or the height for rotated graphs likeGD::Graph::hbar) 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 is 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. Obsessed.
show_valuesβ set this to1to 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. Seey_number_formatfor more information. Default:undef.hide_overlapping_valuesβ if set to a true value, the values that goes out of graph space are hidden. Option is EXPERIMENTAL, works only for bars, text still can overlap with other bars and labels, most useful only with text in the same direction as bars. 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::Graphwill 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 toundef,GD::Graphwill 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_min_rangeβ minimal range of x axis. Default:undef.x_number_formatβ seey_number_format.x_label_skipβ seey_label_skip.
π Options for graphs with bars π
bar_widthβ the width of a bar in pixels. Also seebar_spacing. Usebar_widthif 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 andbar_spacingsetting.bar_spacingβ number of pixels to leave open between bars. This works well in most cases, but on some platforms, a value of1will be rounded off to0. Usebar_spacingto get a fixed amount of space between bars, with variable bar widths, depending on the width of the chart. Note that ifbar_widthis also set, this setting will be ignored, and automatically calculated. Default:0.bargroup_spacingβ number of pixels (in addition to whatever is specified inbar_spacing) to leave between groups of bars when multiple datasets are being displayed. Unlikebar_spacing, however, this parameter will hold its value ifbar_widthis set.
π¦ 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 isundef. For line charts the point gets skipped as well, but the line is drawn between the points n-1 to n+1 directly. Ifskip_undefhas 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 that exist and 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, 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].
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_keyscorrespond to the data sets as provided toplot().
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"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 (BottomorRight), and the second letter the alignment (Left,Right,Center,Top, orBottom). 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 when3dis true. Default:0.1 x height.start_angleβ the angle at which the first data slice will be displayed, with0degrees 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 π
Okay so, every single colour reference in this moduleβs options got shortened to clr. Why? Main reason: I didnβt want to support two spellings for the same word ('colour' and 'color') β literally not the vibe. π
Whenever a colour is required, use a colour name from the package GD::Graph::colour. Run perldoc GD::Graph::colour and you should get the docs for that module, which contains 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. If itβs a TrueType font, bestie, 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). π
π― HOTSPOTS π―
Heads up: 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. No cap. π
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. π
π¨ ERROR HANDLING π¨
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. π
π 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. Periodt. π
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:
- a concise description of the buggy behavior and how it differs from what you expected,
- the versions of Perl,
GD::Graphand GD that you are using, - a short demonstration script that shows the bug in action,
- a patch that fixes it. :-)
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. π
π AUTHOR π
The author lineup, fr fr: Martien Verbruggen <mgjv@tradingpost.com.au>, Benjamin Warfield <bwarfield@cpan.org>, Ruslan Zakirov Best Practical Solutions <modules@bestpractical.com>. π
π 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, 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. π«‘
π SEE ALSO π
GD::Graph::FAQ, GD::Graph::Data, GD::Graph::Error, GD::Graph::colour
Okay bestie, thatβs the whole Graph(3) page β source/version is perl v5.42.0, dated 2024-03-22. Bye, slay, and happy graphing πβ¨
π¦ where this page comes from
- opensuse-leap 16.0: perl-GDGraph 1.560.0-bp160.1.11 Β· (Artistic-1.0 OR GPL-1.0-or-later) AND GPL-2.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms