Lars Lundberg > PDF-Reuse-OverlayChart > PDF::Reuse::OverlayChart

Download:
PDF-Reuse-OverlayChart-0.03.tar.gz

Dependencies

Annotate this POD

View/Report Bugs
Module Version: 0.03   Source  

NAME ^

PDF::Reuse::OverlayChart - Produce simple or mixed charts with PDF::Reuse

SYNOPSIS ^

   use PDF::Reuse::OverlayChart;
   use PDF::Reuse;
   use strict;
  
   prFile('myFile.pdf');
   my $s = PDF::Reuse::OverlayChart->new();

   $s->columns(qw(Month  January February  Mars  April  May June July));
   $s->add(      'Riga',     314,     490,  322,  -965, 736, 120, 239);
   $s->add(      'Helsinki', 389,    -865, -242,     7, 689, 294, 518);
   $s->add(      'Stockholm',456,    -712,  542,   367, 742, 189, 190);
   $s->add(      'Oslo',     622,     533,  674,  1289, 679, -56, 345);
  
   $s->draw(x     => 10,
            y     => 200,
            yUnit => '1000 Euros',
            type  => 'bars');
   prEnd();

DESCRIPTION ^

To draw charts with the help of PDF::Reuse. Currently there are 5 types: 'bars', 'totalbars','percentbars', 'lines' and 'area'.

The charts can be overlaid, so you can mix the types in the same chart. (Except for 'percentbars', which can't be freely combined with the others.) The entities shown, should have something in common, like the unit of the y-axis, but that is not really necessary. It is up to you, what you want to combine and relate.

The object you create is a collection of data, which has a common structure, and which you want to present as a unit. It should consist of arrays or arrays of arrays. All the data of an object should have the same structure, so the module can calculate sums and percentages in a consistent way.

If you want to compare data collections with different structure or very different sizes, you should create different objects, which can be presented and "scaled" more or less independently of each other.

Extracting the examples from this POD

In the beginning of PDF::Reuse::Tutorial there is a snippet of code which can be used to extract the examples from this POD.

Probably the best idea is to run the examples first, before looking at them in detail.

Methods ^

new

    my $s = PDF::Reuse::OverlayChart->new();

Constructor. Mandatory.

You can also create a clone of an object like this:

    my $clone = $s->new();

add

    $s->add('name', value1, value2, ..., valueN);

To define data for the graph.

The name will be put to the right of the graph. It will be the identifier (case sensitive) of the series, so you can add new values afterwards. (Then the values also have to come in exactly the same order.)

The values can be numbers with '-' and '.'. You can also have '' or undef to denote a missing value. If the values contain other characters, the series is interpreted as 'columns'.

The values can be either an array, or an array of arrays (only two levels). Within one object the data should have the same structure. The elements of the top array will be put as columns in the chart.

If you have a text file ('textfile.txt') with a simple 2-dimensional table, like the one here below, you can use each line as parameters to the method. (The value in the upper left corner will refer to the columns to the right, not to the names under it.)

    Month   January February Mars  April  May  June  July
    Riga        314    490    322   -965  736   120   239
    Helsinki    389   -865   -242      7  689   294   518
    Stockholm   456   -712    542    367  742   189   190
    Oslo        622    533    674   1289  679   -56   345

ex. ('example.pl'):

   use PDF::Reuse::OverlayChart;
   use PDF::Reuse;
   use strict;
     
   prFile('myFile.pdf');
   my $s = PDF::Reuse::OverlayChart->new();
   
   open (INFILE, "textfile.txt") || die "Couldn't open textfile.txt, $!\n";
   while (<INFILE>)
   {  my @list = m'(\S+)'og;
      $s->add(@list) if (scalar @list) ;
   }
   close INFILE; 
  
   $s->draw(x     => 10,
            y     => 200,
            yUnit => '1000 Euros',
            type  => 'bars');
   prEnd();

columns

    $s->columns( qw(unit column1 column2 .. columnN));

Defines what you want to write along the x-axis. The first value will be put to the right of the arrow of the axis. It could be the "unit" of the columns.

draw

This method does the actual "plotting" of the graph. The parameters are

x

x-coordinate of the lower left corner in pixels, where the graph is going to be drawn. The actual graph comes still a few pixels to the right.

y

y-coordinate of the lower left corner in pixels, where the graph is going to be drawn. The actual graph comes still a few pixels higher up.

width

Width of the graph. 450 by default. Long texts might end up outside.

height

Height of the graph. 450 by default.

size

A number to resize the graph, with lines, texts and everything

(If you change the size of a graph with the parameters width and height, the font sizes, distances between lines etc. are untouched, but with 'size' they also change.)

xsize

A number to resize the graph horizontally, with lines, texts and everything

ySize

A number to resize the graph vertically, with lines, texts and everything

type

By default: 'bars'. Can also be 'totalbars', percentbars', 'lines' and 'area', (you could abbreviate to the first character if you want).

When you have 'lines' or 'area', you get vertical lines. They show where the values of the graph are significant. The values between these points are possible, but of course not necessarily true. It is an illustration.

yUnit

What to write above the y-axis

background

Three RGB numbers ex. '0.95 0.95 0.95'.

noUnits

If this parameter is equal to 1, no units are written.

title

Title above the chart

groupsTitle

Titel above the column to the right of the chart

groupsText

Text under groupsTitle

initialMaxY

To force the program start with a specific max (positive) value for the scale along the y-axis.

initialMinY

To force the program start with a specific min (negative) value for the scale along the y-axis.

merge

To merge different graph-objects into one chart. The graph-objects should be put in an anonymous array. Each graph-object should use the "overlay" method. Ex :

   $val->draw(x            => 20,
              y            => 460,
              width        => 400,
              height       => 300,
              type         => 'lines',
              noMarker     => 1, 
              groupstitle  => 'Left Scale',
              title        => 'Amazon',
              yUnit        => 'USD',
              merge        => [ $sek->overlay    ( type         => 'lines',
                                                   yDensity     => $sekDensity,
                                                   noMarker     => 1),
                                $spIndex->overlay( type         => 'lines',
                                                   yDensity     => $spDensity,
                                                   noMarker     => 1),
                                $vol->overlay    ( type         => 'area',
                                                   rightScale   => 1,
                                                   yDensity     => $volumeDensity,
                                                   groupstitle  => 'Right Scale'),] );

In the example above 4 objects are combined into 1 chart. Each object can have its' own density (but it is not necessary) and some other characteristics described under "overlay". The objects are painted in reversed order: $vol, $spIndex, $sek and at last $val, which automatically gets the left scale and also the normative density of the chart. (Interactive functions for each object are also imported.)

The merge parameter is ignored, if the type of the main object is percentbars

noMarker

Only for lines. No markers will be painted.

noGroups

To suppress the names of the groups, so they will not be printed to the right of the chart.

color

   $s->color( ('1 1 0', '0 1 1', '0 1 0', '1 0 0', '0 0 1'));

To define colors to be used. The parameter to this method is a list of RGB numbers.

You can also use some predefined color arrays: 'bright', 'dark', 'gray' or 'light', but only one at a time. Then you get 10 predefined colors ex:

   $s-color('dark');  

If the module needs more colors than what has been given in the script, it creates more, just from random numbers.

overlay

Defines how an imported graph-object should be painted. See the parameter merge under draw for an example.

Parameters:

type

Can be bars, totalbars, lines and area, but not percentbars.

rightScale

If many objects have this parameter, only the first object will have a right scale painted, and the "yDensity" of the scale will be derived from that object.

topScale

If many objects have this parameter, only the first object will have a top scale painted, and the "xDensity" of the scale will be derived from that object. If that object has some column labels defined (with the columns method), they will also be used here.

noMarker

Only for lines. No markers will be painted.

noGroups

To suppress the names of the groups, so they will not be printed to the right of the chart.

xDensity

Density along the x-axis, a numeric value, possibly with decimals. If it is 10, it denotes that 10 units along the x-axis in this sub chart corresponds to 1 unit in the main chart. If it is 0.1, 1 unit in this chart corresponds to 10 units in the main chart

yDensity

Density along the y-axis, a numeric value, possibly with decimals. If it is 10, it denotes that 10 units along the y-axis in this sub chart corresponds to 1 unit in the main chart.

A simple example ^

An invented company with a few offices.

   use PDF::Reuse::OverlayChart;
   use PDF::Reuse;
   use strict;
     
   prFile('myFile.pdf');
   prCompress(1);
   my $s = PDF::Reuse::OverlayChart->new();

   ###########
   # Money in
   ###########

   $s->columns( qw(Month   January February Mars  April  May  June  July));
   $s->add(     qw(Riga        436   790     579   1023   964  520    390));
   $s->add(     qw(Helsinki    529   630     789    567   570   94    180));
   $s->add(     qw(Stockholm   469   534     642    767   712  399    190));
   $s->add(     qw(Oslo        569   833     967   1589   790  158    345));

   $s->draw(x      => 45,
            y      => 455,
            yUnit  => '1000 Euros',
            type   => 'bars',
            title  => 'Money In',
            height => 300,
            width  => 460);

   ###################################
   # Costs are to be shown separately
   ###################################

   my $costs = PDF::Reuse::OverlayChart->new();
   
   $costs->columns( qw(Month   January February Mars April  May  June  July));
   $costs->add(     qw(Riga        -316  -290  -376   -823 -243  -320  -509));
   $costs->add(     qw(Helsinki    -440  -830  -989   -671 -170  -394  -618));
   $costs->add(     qw(Stockholm   -218  -345  -242   -467 -412  -299  -590));
   $costs->add(     qw(Oslo        -369  -343  -567   -589 -390  -258  -459));

   $costs->draw(x      => 45,
                y      => 55,
                yUnit  => '1000 Euros',
                type   => 'bars',
                title  => 'Costs',
                height => 300,
                width  => 460);

   ####################################
   # The costs are added to 'money in'
   ####################################

   $s->add( qw(Riga        -316  -290  -376   -823 -243  -320  -509));
   $s->add( qw(Helsinki    -440  -830  -989   -671 -170  -394  -618));
   $s->add( qw(Stockholm   -218  -345  -242   -467 -412  -299  -590));
   $s->add( qw(Oslo        -369  -343  -567   -589 -390  -258  -459));

   prPage();

   $s->draw(x     => 45,
            y     => 455,
            yUnit => '1000 Euros',
            type  => 'bars',
            title => 'Profit');

   ########
   # Taxes
   ########

   $s->add( qw(Riga        -116  -90   -179   -230  -43  -20  -90));
   $s->add( qw(Helsinki     40   -130  -190   -32   -70  -30  -18));
   $s->add( qw(Stockholm    28   -45   -42    -107  -92  -99  -90));
   $s->add( qw(Oslo        -169  -43   -67    -189  -190 -58  -59));

   $s->draw(x     => 45,
            y     => 55,
            yUnit => '1000 Euros',
            type  => 'bars',
            title => 'After Tax');

    prEnd();

An example how to mix different graph types in the same chart ^

In this example you let a program collect historical quotes for 'Amazon', approximately 1 year back, and also values for 'S&P 100' and then you get a chart with combined data, an area graph for volumes, and lines for the other values. (You need to have the environment variable TZ defined somewhere, see Date::Manip, which is a module needed by Finance::QuoteHist. TZ, time zone, could e.g. be CET or GMT in Western Europe.)

   use PDF::Reuse::OverlayChart;
   use Finance::QuoteHist;
   use PDF::Reuse;
   use strict;

   #################
   # Some variables
   #################
   my (%values, @values, %volumes, @volumes, %sp100, @sp100, $startValue, 
       $startSpValue);
   my $maxVolume = 0;
   my $maxValue  = 0;
   my $month = sprintf("%02d", ((localtime())[4]) + 1);
   my $lastYear = sprintf("%04d", ((localtime())[5] + 1900 - 1));
   my $aYearAgo = "$month/01/$lastYear";

   prFile('myFile.pdf');
   prCompress(1);
    
   ###########################################################
   # Get historical quotes via the web for Amazon and S&P100
   ###########################################################

   my $q = Finance::QuoteHist->new ( symbols    => [qw(AMZN ^OEX)],
                                     start_date => $aYearAgo,
                                     end_date   => 'today',);

   ##################################
   # Accumulate the values in hashes
   ##################################

   for my $row ($q->quotes()) 
   {  my ($symbol, $date, $open, $high, $low, $close, $volume) = @$row;
      if ($date =~ m'(\d+\/\d+)\/(\d+)'o)
      {   my $yearMonth = $1;
          my $day       = $2;
          if ($symbol ne '^OEX')
          {   $volume = sprintf("%.0f", ($volume / 1000000));
              $values{$yearMonth}->[$day]  = $close  if ($close);
              $volumes{$yearMonth}->[$day] = $volume if ($volume);
              $maxVolume  = $volume if $volume > $maxVolume;
              $maxValue   = $close  if $close  > $maxValue;
              $startValue = $close  if (! defined $startValue);
          }
          else
          {   $sp100{$yearMonth}->[$day]  = $close if ($close);
              $startSpValue               = $close if (!defined $startSpValue);
          }
      }
   }

   my @keys = sort (keys %volumes);
   my $i;

   ##########################################
   # Make one array of arrays of the volumes
   ##########################################

   for my $key  (@keys)
   {   my @array;
       for (@{$volumes{$key}})
       {  push @array, $_ if $_;        # Only days with trade
       }
       for ($i = $#array; $i < 18; $i++)
       {  push @array, undef;           # Fill the month, if not complete
       }
       push @volumes, [@array];         # One array per month is pushed to volumes
   }

   #################################################
   # Make one array of arrays of the closing values
   #################################################

   for my $key  (@keys)
   {   my @array;
       for (@{$values{$key}})
       {   push @array, $_ if $_;
       }
       for ($i = $#array; $i < 18; $i++)
       {  push @array, undef;
       }
       push @values, [@array];
   }

   ##########################################################
   # Make one array of arrays of the closing values of SP100
   ##########################################################

   for my $key  (@keys)
   {   my @array;
       for (@{$sp100{$key}})
       {   push @array, $_ if $_;
       }
       for ($i = $#array; $i < 18; $i++)
       {  push @array, undef;
       }
       push @sp100, [@array];
   }

   #########################################################################
   # Calculate a suitable density for the volumes so they fill up the chart 
   #########################################################################

   my $volumeDensity = sprintf("%.6f", ($maxVolume / $maxValue));

   ################################################################
   # Make the density for S&P 100 so it gets a good starting point
   ################################################################

   my $spDensity = sprintf("%.1f", ($startSpValue / $startValue));

   ########################################
   # Create and populate the chart-objects
   ########################################

   my $vol = PDF::Reuse::OverlayChart->new();
   $vol->add('Volume (1/1000000)', ( @volumes ));
   $vol->color('dark');

   my $val = PDF::Reuse::OverlayChart->new();
   $val->columns('Month', ( @keys ) ); 
   $val->add('Closing Value USD', ( @values ));
   $val->color('bright');

   my $spIndex = PDF::Reuse::OverlayChart->new();
   $spIndex->add("S&P 100 (1/$spDensity)", ( @sp100 ));
   $spIndex->color( ('0 0 0') );  

   #####################
   # Now draw the chart
   #####################

   $val->draw(x            => 20,
              y            => 460,
              width        => 400,
              height       => 300,
              type         => 'lines',
              noMarker     => 1, 
              groupstitle  => 'Left Scale',
              title        => 'Amazon',
              merge        => [ $spIndex->overlay( type         => 'lines',
                                                   yDensity     => $spDensity,
                                                   noMarker     => 1),
                                $vol->overlay    ( type         => 'area',
                                                   rightScale   => 1,
                                                   yDensity     => $volumeDensity,
                                                   groupstitle  => 'Right Scale')] );
 
   prEnd();

Comments about the example:

All the values are put in arrays of arrays like this:

    [  [day1 ... dayN],    # This is the first month
       [day1 ... dayN],    # Next month
       ...
       [day1 ... dayN]]    # Last month

In the chart there will be one column for each month. The column labels will be taken from the main object.

The 3 different chart-objects have different density along the y-axis (yDensity). The main chart-object, '$val', gets a value automatically calculated. It cannot be directly influenced. The other objects can get a yDensity defined. Then it is always related to the main object. To make the S&P 100 index start in the same point as the first closing value for Amazon ($startValue), the yDensity for the index-graph is calculated like this:

   my $spDensity = sprintf("%.1f", ($startSpValue / $startValue));

To make the graph for volumes fill the chart, the maximum values are coordinated in a similar way:

   my $volumeDensity = sprintf("%.6f", ($maxVolume / $maxValue));

When the combined chart is drawn, the charts are painted in reversed order, so the main cart is pained last. It also automatically gets the left scale.

SEE ALSO ^

   PDF::Reuse
   PDF::Reuse::Tutorial

MAILING LIST ^

   http://groups.google.com/group/PDF-Reuse

AUTHOR ^

Lars Lundberg, larslund@cpan.org

COPYRIGHT AND LICENSE ^

Copyright (C) 2004 - 2005 by Lars Lundberg

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

DISCLAIMER ^

You get this module free as it is, but nothing is guaranteed to work, whatever implicitly or explicitly stated in this document, and everything you do, you do at your own risk - I will not take responsibility for any damage, loss of money and/or health that may arise from the use of this module.

syntax highlighting: