return missing font errors in from the error method, add tests for the
[imager-graph.git] / lib / Imager / Graph / Pie.pm
CommitLineData
35574351
TC
1package Imager::Graph::Pie;
2
3=head1 NAME
4
5 Imager::Graph::Pie - a tool for drawing pie charts on Imager images
6
7=head1 SYNOPSIS
8
9 use Imager::Graph::Pie;
10
11 my $chart = Imager::Graph::Pie->new;
12 # see Imager::Graph for options
81453d28 13 my $img = $chart->draw(
14 data => [ $first_amount, $second_amount ],
15 size => 350);
35574351
TC
16
17=head1 DESCRIPTION
18
19Imager::Graph::Pie is intender to make it simple to use L<Imager> to
20create good looking pie graphs.
21
22Most of the basic layout and color selection is handed off to
23L<Imager::Graph>.
24
25=over
26
27=cut
28
29use strict;
30use vars qw(@ISA);
31use Imager::Graph;
32@ISA = qw(Imager::Graph);
33use Imager::Graph::Util;
34use POSIX qw(floor);
35
36use constant PI => 3.1415926535;
37
35574351
TC
38=item $graph->draw(...)
39
40Draws a pie graph onto a new image and returns the image.
41
81453d28 42You must at least supply a C<data> parameter and should probably supply a C<labels> parameter. If you supply a C<labels> parameter, you must supply a C<font> parameter.
35574351
TC
43
44The C<data> parameter should be a reference to an array containing the
45data the pie graph should present.
46
47The C<labels> parameter is a reference to an array of labels,
48corresponding to the values in C<data>.
49
50=back
51
52=head1 FEATURES
53
54As described in L<Imager::Graph> you can enable extra features for
55your graph. The features you can use with pie graphs are:
56
57=over
58
59=item legend
60
61adds a legend to your graph. Requires the labels parameter
62
63=item labels
64
65labels each segment of the graph. If the label doesn't fit inside the
66segment it is presented as a callout.
67
68=item labelspc
69
70adds the percentage of the pie to each label.
71
72=item labelspconly
73
74the segments are labels with their percentages only.
75
76=item allcallouts
77
78all labels are presented as callouts
79
35574351
TC
80=item outline
81
82the pie segments are outlined.
83
84=item dropshadow
85
86the pie is given a drop shadow.
87
88=back
89
320f5a49
TC
90=head1 PIE CHART STYLES
91
92The following style values are specific to pie charts:
93
94Controlling callouts, the C<callout> option:
95
96=over
97
98=item *
99
100color - the color of the callout line and the callout text.
101
102=item *
103
104font, size - font and size of the callout text
105
106=item *
107
108outside - the distance the radial callout line goes outside the pie
109
110=item *
111
112leadlen - the length of the horizontal callout line from the end of
113the radial line.
114
115=item *
116
117gap - the distance between the end of the horizontal callout line and
118the label.
119
120=item *
121
122inside - the length of the radial callout line within the pie.
123
124=back
125
126The outline, line option controls the color of the pie segment
127outlines, if enabled with the C<outline> feature.
128
129Under C<pie>:
130
131=over
132
133=item *
134
135maxsegment - any segment below this fraction of the total of the
136segments will be put into the "others" segment. Default: 0.01
137
138=back
139
140The top level C<otherlabel> setting controls the label for the
141"others" segment, default "(others)".
142
35574351
TC
143=head1 EXAMPLES
144
145Assuming:
146
147 # from the Netcraft September 2001 web survey
148 # http://www.netcraft.com/survey/
149 my @data = qw(17874757 8146372 1321544 811406 );
150 my @labels = qw(Apache Microsoft iPlanet Zeus );
151
152 my $pie = Imager::Graph::Pie->new;
153
154First a simple graph, normal size, no labels:
155
156 my $img = $pie->draw(data=>\@data)
157 or die $pie->error;
158
159label the segments:
160
161 # error handling omitted for brevity from now on
162 $img = $pie->draw(data=>\@data, labels=>\@labels, features=>'labels');
163
164just percentages in the segments:
165
166 $img = $pie->draw(data=>\@data, features=>'labelspconly');
167
168add a legend as well:
169
170 $img = $pie->draw(data=>\@data, labels=>\@labels,
171 features=>[ 'labelspconly', 'legend' ]);
172
173and a title, but move the legend down, and add a dropshadow:
174
175 $img = $pie->draw(data=>\@data, labels=>\@labels,
176 title=>'Netcraft Web Survey',
177 legend=>{ valign=>'bottom' },
178 features=>[ qw/labelspconly legend dropshadow/ ]);
179
180something a bit prettier:
181
182 # requires Imager > 0.38
183 $img = $pie->draw(data=>\@data, labels=>\@labels,
184 style=>'fount_lin', features=>'legend');
185
186suitable for monochrome output:
187
188 # requires Imager > 0.38
189 $img = $pie->draw(data=>\@data, labels=>\@labels,
190 style=>'mono', features=>'legend');
191
192=cut
193
194# this function is too long
195sub draw {
196 my ($self, %opts) = @_;
197
198 $opts{data}
199 or return $self->_error("No data parameter supplied");
200 my @data = @{$opts{data}};
201 my @labels;
202 @labels = @{$opts{labels}} if $opts{labels};
203
204 $self->_style_setup(\%opts);
205
206 my $style = $self->{_style};
207
208 my $img = $self->_make_img()
209 or return;
210
211 my $total = 0;
212 for my $item (@data) {
213 $total += $item;
214 }
215
216 my @chart_box = ( 0, 0, $img->getwidth-1, $img->getheight-1 );
217 if ($style->{title}{text}) {
218 $self->_draw_title($img, \@chart_box)
219 or return;
220 }
221
222 # consolidate any segments that are too small to display
223 $self->_consolidate_segments(\@data, \@labels, $total);
224
225 if ($style->{features}{legend} && $opts{labels}) {
226 $self->_draw_legend($img, \@labels, \@chart_box)
227 or return;
228 }
229
230 # the following code is fairly ugly
231 # it attempts to work out a good layout for the components of the chart
232 my @info;
233 my $index = 0;
234 my $pos = 0;
235 my @ebox = (0, 0, 0, 0);
236 defined(my $callout_outside = $self->_get_number('callout.outside'))
237 or return;
238 defined(my $callout_leadlen = $self->_get_number('callout.leadlen'))
239 or return;
240 defined(my $callout_gap = $self->_get_number('callout.gap'))
241 or return;
242 defined(my $label_vpad = $self->_get_number('label.vpad'))
243 or return;
244 defined(my $label_hpad = $self->_get_number('label.hpad'))
245 or return;
246 my $guessradius =
247 int($self->_small_extent(\@chart_box) * $style->{pie}{guessfactor} * 0.5);
248 for my $data (@data) {
249 my $item = { data=>$data, index=>$index };
250 my $size = 2 * PI * $data / $total;
251 $item->{begin} = $pos;
252 $pos += $size;
253 $item->{end} = $pos;
254 if ($opts{labels}) {
255 $item->{text} = $labels[$index];
256 }
257 if ($style->{features}{labelspconly}) {
258 $item->{text} =
259 $style->{label}{pconlyformat}->($data/$total * 100);
260 }
261 if ($item->{text}) {
262 if ($style->{features}{labelspc}) {
263 $item->{text} =
264 $style->{label}{pcformat}->($item->{text}, $data/$total * 100);
265 $item->{label} = 1;
266 }
267 elsif ($style->{features}{labelspconly}) {
268 $item->{text} =
269 $style->{label}{pconlyformat}->($data/$total * 100);
270 $item->{label} = 1;
271 }
272 elsif ($style->{features}{labels}) {
273 $item->{label} = 1;
274 }
5d622bb8
TC
275 my @lbox = $self->_text_bbox($item->{text}, 'label')
276 or return;
277 $item->{lbox} = \@lbox;
35574351
TC
278 if ($item->{label}) {
279 unless ($self->_fit_text(0, 0, 'label', $item->{text}, $guessradius,
280 $item->{begin}, $item->{end})) {
281 $item->{callout} = 1;
282 }
283 }
284 $item->{callout} = 1 if $style->{features}{allcallouts};
285 if ($item->{callout}) {
286 $item->{label} = 0;
5d622bb8
TC
287 my @cbox = $self->_text_bbox($item->{text}, 'callout')
288 or return;
289 $item->{cbox} = \@cbox;
35574351
TC
290 $item->{cangle} = ($item->{begin} + $item->{end}) / 2;
291 my $dist = cos($item->{cangle}) * ($guessradius+
292 $callout_outside);
293 my $co_size = $callout_leadlen + $callout_gap + $item->{cbox}[2];
294 if ($dist < 0) {
295 $dist -= $co_size - $guessradius;
296 $dist < $ebox[0] and $ebox[0] = $dist;
297 }
298 else {
299 $dist += $co_size - $guessradius;
300 $dist > $ebox[2] and $ebox[2] = $dist;
301 }
302 }
303 }
304 push(@info, $item);
305 ++$index;
306 }
307
308 my $radius =
309 int($self->_small_extent(\@chart_box) * $style->{pie}{size} * 0.5);
310 my $max_width = $chart_box[2] - $chart_box[0] + $ebox[0] - $ebox[2];
311 if ($radius > $max_width / 2) {
3c9a5609 312 $radius = int($max_width / 2);
35574351
TC
313 }
314 $chart_box[0] -= $ebox[0];
315 $chart_box[2] -= $ebox[2];
316 my $cx = int(($chart_box[0] + $chart_box[2]) / 2);
317 my $cy = int(($chart_box[1] + $chart_box[3]) / 2);
318 if ($style->{features}{dropshadow}) {
319 my @shadow_fill = $self->_get_fill('dropshadow.fill')
320 or return;
321 my $offx = $self->_get_number('dropshadow.offx')
322 or return;
323 my $offy = $self->_get_number('dropshadow.offy');
324 for my $item (@info) {
bfcf9414 325 $img->arc(x=>$cx+$offx, 'y'=>$cy+$offy, r=>$radius+1, aa => 1,
35574351
TC
326 d1=>180/PI * $item->{begin}, d2=>180/PI * $item->{end},
327 @shadow_fill);
328 }
329 $self->_filter_region($img,
330 $cx+$offx-$radius-10, $cy+$offy-$radius-10,
331 $cx+$offx+$radius+10, $cy+$offy+$radius+10,
332 'dropshadow.filter')
333 if $style->{dropshadow}{filter};
334 }
bfcf9414 335
35574351
TC
336 my @fill_box = ( $cx-$radius, $cy-$radius, $cx+$radius, $cy+$radius );
337 for my $item (@info) {
26c93f46
TC
338 $item->{begin} < $item->{end}
339 or next;
35574351
TC
340 my @fill = $self->_data_fill($item->{index}, \@fill_box)
341 or return;
bfcf9414 342 $img->arc(x=>$cx, 'y'=>$cy, r=>$radius, aa => 1,
35574351
TC
343 d1=>180/PI * $item->{begin}, d2=>180/PI * $item->{end},
344 @fill);
345 }
35574351
TC
346 if ($style->{features}{outline}) {
347 my $outcolor = $self->_get_color('outline.line');
348 for my $item (@info) {
bfcf9414
TC
349 my $px = int($cx + $radius * cos($item->{begin}));
350 my $py = int($cy + $radius * sin($item->{begin}));
26c93f46
TC
351 $item->{begin} < $item->{end}
352 or next;
35574351
TC
353 $img->line(x1=>$cx, y1=>$cy, x2=>$px, y2=>$py, color=>$outcolor);
354 for (my $i = $item->{begin}; $i < $item->{end}; $i += PI/180) {
355 my $stroke_end = $i + PI/180;
356 $stroke_end = $item->{end} if $stroke_end > $item->{end};
bfcf9414
TC
357 my $nx = int($cx + $radius * cos($stroke_end));
358 my $ny = int($cy + $radius * sin($stroke_end));
35574351
TC
359 $img->line(x1=>$px, y1=>$py, x2=>$nx, y2=>$ny, color=>$outcolor,
360 antialias=>1);
361 ($px, $py) = ($nx, $ny);
362 }
363 }
364 }
365
366 my $callout_inside = $radius - $self->_get_number('callout.inside');
367 $callout_outside += $radius;
5d622bb8
TC
368 my %callout_text = $self->_text_style('callout')
369 or return;
370 my %label_text = $self->_text_style('label')
371 or return;
35574351
TC
372 for my $label (@info) {
373 if ($label->{label}) {
374 my @loc = $self->_fit_text($cx, $cy, 'label', $label->{text}, $radius,
375 $label->{begin}, $label->{end});
376 if (@loc) {
377 my $tcx = ($loc[0]+$loc[2])/2;
378 my $tcy = ($loc[1]+$loc[3])/2;
379 #$img->box(xmin=>$loc[0], ymin=>$loc[1], xmax=>$loc[2], ymax=>$loc[3],
380 # color=>Imager::Color->new(0,0,0));
381 $img->string(%label_text, x=>$tcx-$label->{lbox}[2]/2,
382 'y'=>$tcy+$label->{lbox}[3]/2+$label->{lbox}[1],
383 text=>$label->{text});
384 }
385 else {
386 $label->{callout} = 1;
5d622bb8
TC
387 my @cbox = $self->_text_bbox($label->{text}, 'callout')
388 or return;
389 $label->{cbox} = \@cbox;
35574351
TC
390 $label->{cangle} = ($label->{begin} + $label->{end}) / 2;
391 }
392 }
393 if ($label->{callout}) {
394 my $ix = floor(0.5 + $cx + $callout_inside * cos($label->{cangle}));
395 my $iy = floor(0.5 + $cy + $callout_inside * sin($label->{cangle}));
396 my $ox = floor(0.5 + $cx + $callout_outside * cos($label->{cangle}));
397 my $oy = floor(0.5 + $cy + $callout_outside * sin($label->{cangle}));
398 my $lx = ($ox < $cx) ? $ox - $callout_leadlen : $ox + $callout_leadlen;
399 $img->line(x1=>$ix, y1=>$iy, x2=>$ox, y2=>$oy, antialias=>1,
400 color=>$self->_get_color('callout.color'));
401 $img->line(x1=>$ox, y1=>$oy, x2=>$lx, y2=>$oy, antialias=>1,
402 color=>$self->_get_color('callout.color'));
403 #my $tx = $lx + $callout_gap;
404 my $ty = $oy + $label->{cbox}[3]/2+$label->{cbox}[1];
405 if ($lx < $cx) {
406 $img->string(%callout_text, x=>$lx-$callout_gap-$label->{cbox}[2],
407 'y'=>$ty, text=>$label->{text});
408 }
409 else {
410 $img->string(%callout_text, x=>$lx+$callout_gap, 'y'=>$ty,
411 text=>$label->{text});
412 }
413 }
414 }
415
416 $img;
417}
418
419=head1 INTERNAL FUNCTIONS
420
421These are used in the implementation of Imager::Graph, and are
422documented for debuggers and developers.
423
424=over
425
426=item _consolidate_segments($data, $labels, $total)
427
428Consolidate segments that are too small into an 'others' segment.
429
430=cut
431
432sub _consolidate_segments {
433 my ($self, $data, $labels, $total) = @_;
434
435 my @others;
436 my $index;
437 for my $item (@$data) {
438 if ($item / $total < $self->{_style}{pie}{maxsegment}) {
439 push(@others, $index);
440 }
441 ++$index;
442 }
443 if (@others) {
444 my $others = 0;
445 for my $index (reverse @others) {
446 $others += $data->[$index];
447 splice(@$labels, $index, 1);
448 splice(@$data, $index, 1);
449 }
450 push(@$labels, $self->{_style}{otherlabel}) if @$labels;
451 push(@$data, $others);
452 }
453}
454
35574351
TC
455# used for debugging
456sub _test_line {
457 my ($x, $y, @l) = @_;
458
459 my $res = $l[0]*$x + $l[1] * $y + $l[2];
460 print "test ", (abs($res) < 0.000001) ? "success\n" : "failure $res\n";
461}
462
463=item _fit_text($cx, $cy, $name, $text, $radius, $begin, $end)
464
465Attempts to fit text into a pie segment with its center at ($cx, $cy)
466with the given radius, covering the angles $begin through $end.
467
468Returns a list defining the bounding box of the text if it does fit.
469
470=cut
471
472sub _fit_text {
473 my ($self, $cx, $cy, $name, $text, $radius, $begin, $end) = @_;
474
475 #print "fit: $cx, $cy '$text' $radius $begin $end\n";
476 my @tbox = $self->_text_bbox($text, $name);
477 my $tcx = floor(0.5+$cx + cos(($begin+$end)/2) * $radius *3/5);
478 my $tcy = floor(0.5+$cy + sin(($begin+$end)/2) * $radius *3/5);
479 my $topy = $tcy - $tbox[3]/2;
480 my $boty = $topy + $tbox[3];
481 my @lines;
482 for my $y ($topy, $boty) {
483 my %entry = ( 'y'=>$y );
484 $entry{line} = [ line_from_points($tcx, $y, $tcx+1, $y) ];
485 $entry{left} = -$radius;
486 $entry{right} = $radius;
487 for my $angle ($begin, $end) {
488 my $ex = $cx + cos($angle)*$radius;
489 my $ey = $cy + sin($angle)*$radius;
490 my @line = line_from_points($cx, $cy, $ex, $ey);
491 #_test_line($cx, $cy, @line);
492 #_test_line($ex, $ey, @line);
493 my $goodsign = $line[0] * $tcx + $line[1] * $tcy + $line[2];
494 for my $pos (@entry{qw/left right/}) {
495 my $sign = $line[0] * ($pos+$tcx) + $line[1] * $y + $line[2];
496 if ($goodsign * $sign < 0) {
497 if (my @p = intersect_lines(@line, @{$entry{line}})) {
498 # die "$goodsign $sign ($pos, $tcx) no intersect (@line) (@{$entry{line}})" ; # this would be wierd
499 #_test_line(@p, @line);
500 #_test_line(@p, @{$entry{line}});
501 $pos = $p[0]-$tcx;
502 }
503 else {
504 return;
505 }
506
507 }
508
509 # circle
510 my $dist2 = ($pos+$tcx-$cx) * ($pos+$tcx-$cx)
511 + ($y - $cy) * ($y - $cy);
512 if ($dist2 > $radius * $radius) {
513 my @points =
514 intersect_line_and_circle(@{$entry{line}}, $cx, $cy, $radius);
515 while (@points) {
516 my @p = splice(@points, 0, 2);
517 if ($p[0] < $cx && $tcx+$pos < $p[0]) {
518 $pos = $p[0]-$tcx;
519 }
520 elsif ($p[0] > $cx && $tcx+$pos > $p[0]) {
521 $pos = $p[0]-$tcx;
522 }
523 }
524 }
525 }
526 }
527 push(@lines, \%entry);
528 }
529 my $left = $lines[0]{left} > $lines[1]{left} ? $lines[0]{left} : $lines[1]{left};
530 my $right = $lines[0]{right} < $lines[1]{right} ? $lines[0]{right} : $lines[1]{right};
531 return if $right - $left < $tbox[2];
532
533 return ($tcx+$left, $topy, $tcx+$right, $boty);
534}
535
536sub _composite {
537 ( 'pie', $_[0]->SUPER::_composite() );
538}
539
540sub _style_defs {
541 my ($self) = @_;
542
543 my %work = %{$self->SUPER::_style_defs()};
544 $work{otherlabel} = "(others)";
35574351
TC
545 $work{pie} =
546 {
35574351
TC
547 guessfactor=>0.6,
548 size=>0.8,
320f5a49 549 maxsegment=> 0.01,
35574351
TC
550 };
551
552 \%work;
553}
554
5551;
556__END__
557
54ada35d
TC
558=back
559
35574351
TC
560=head1 AUTHOR
561
562Tony Cook <tony@develop-help.com>
563
564=head1 SEE ALSO
565
566Imager::Graph(3), Imager(3), perl(1)
567
568=cut