Chart-Gnuplot

 view release on metacpan or  search on metacpan

lib/Chart/Gnuplot.pm  view on Meta::CPAN

        elsif ($attr =~ /^((x|y)2?|z)label$/)
        {
            print PLT "set $attr ".&_setAxisLabel($self->{$attr})."\n";
            push(@sets, $attr);
        }
        elsif ($attr =~ /^((x|y)2?|z|t|u|v)range$/)
        {
            if (ref($self->{$attr}) eq 'ARRAY')
            {
                # Deal with ranges from array reference
                if (defined $self->{timeaxis} &&
                    $self->{timeaxis} =~ /(^|,)\s*$1\s*(,|$)/)
                {
                    # $1-axis is a time axis
                    print PLT "set $attr ['".join("':'", @{$self->{$attr}}).
                        "']\n";
                }
                else
                {
                    print PLT "set $attr [".join(":", @{$self->{$attr}})."]\n";
                }
            }
            elsif ($self->{$attr} eq 'reverse')
            {
                print PLT "set $attr [*:*] reverse\n";
            }
            else
            {
                print PLT "set $attr $self->{$attr}\n";
            }
            push(@sets, $attr);
        }
        elsif ($attr =~ /^(x|y|x2|y2|z)tics$/)
        {
            if (defined $self->{$attr})
            {
                my ($axis) = ($attr =~ /^(.+)tics$/);
                print PLT "set $attr".&_setTics($self->{$attr})."\n";
                if (ref($self->{$attr}) eq 'HASH')
                {
                    if (defined ${$self->{$attr}}{labelfmt})
                    {
                        print PLT "set format $axis ".
                            "\"${$self->{$attr}}{labelfmt}\"\n";
                        push(@sets, 'format');
                    }
                    if (defined ${$self->{$attr}}{minor})
                    {
                        my $nTics = ${$self->{$attr}}{minor}+1;
                        print PLT "set m$axis"."tics $nTics\n";
                        push(@sets, "m$axis"."tics");
                    }
                }
                push(@sets, $attr);
            }
            else
            {
                print PLT "unset $attr\n";
            }
        }
        elsif ($attr eq 'legend')
        {
            print PLT "set key".&_setLegend($self->{legend})."\n";
            push(@sets, 'key');
        }
        elsif ($attr eq 'border')
        {
            if (defined $self->{border})
            {
                print PLT "set border";
                print PLT " ".&_borderCode($self->{border}->{sides}) if
                    (defined $self->{border}->{sides});
                print PLT &_setBorder($self->{border})."\n";
                push(@sets, 'border');
            }
            else
            {
                print PLT "unset border\n";
            }
        }
        elsif ($attr =~ /^(minor)?grid$/)
        {
            next if ($setGrid == 1);

            print PLT "set grid".&_setGrid($self)."\n";
            push(@sets, 'grid');
            $setGrid = 1;
        }
        elsif ($attr eq 'timestamp')
        {
            print PLT "set timestamp".&_setTimestamp($self->{timestamp})."\n";
            push(@sets, 'timestamp');
        }
        elsif ($attr eq 'terminal')
        {
            print PLT "set $attr $self->{$attr}\n";
        }
        # Non-gnuplot options / options specially treated before
        elsif (!grep(/^$attr$/, qw(
                gnuplot
                convert
                encoding
                imagesize
                orient
                bg
                plotbg
                timeaxis
            )) &&
            $attr !~ /^_/)
        {
            (defined $self->{$attr} && $self->{$attr} ne '')?
                (print PLT "set $attr $self->{$attr}\n"):
                (print PLT "set $attr\n");
            push(@sets, $attr);
        }
    }

    # Write labels
	my $isLabelSet = 0;
    foreach my $label (@{$self->{_labels}})
    {
        print PLT "set label"."$label\n";
		push(@sets, "label") if ($isLabelSet == 0);

lib/Chart/Gnuplot.pm  view on Meta::CPAN

            ($majorType, $minorType) = split(/\,\s?/, $$grid{linetype}) if
                ($$grid{linetype} =~ /\,/);
        }
        $minorType = $$mgrid{linetype} if (defined $$mgrid{linetype});
        $major .= " linetype ".&_lineType($majorType);
        $minor .= " linetype ".&_lineType($minorType);
        
        # Set the line width of the grid lines
        my $majorWidth = my $minorWidth = 0;
        if (defined $$grid{width})
        {
            $majorWidth = $minorWidth = $$grid{width};
            ($majorWidth, $minorWidth) = split(/\,\s?/, $$grid{width}) if
                ($$grid{width} =~ /\,/);
        }
        $minorWidth = $$mgrid{width} if (defined $$mgrid{width});
        $major .= " linewidth $majorWidth";
        $minor .= " linewidth $minorWidth";

        # Set the line color of the grid lines
        my $majorColor = my $minorColor = 'black';
        if (defined $$grid{color})
        {
            $majorColor = $minorColor = $$grid{color};
            ($majorColor, $minorColor) = split(/\,\s?/, $$grid{color}) if
                ($$grid{color} =~ /\,/);
        }
        $minorColor = $$mgrid{color} if (defined $$mgrid{color});
        $major .= " linecolor rgb \"$majorColor\"";
        $minor .= " linecolor rgb \"$minorColor\"";
        $out .= "$major" if ($major ne '');
        $out .= ",$minor" if ($minor ne '');
    }
    else
    {
        if (defined $grid)
        {
            return(" $grid") if ($grid !~ /^(on|off)$/);
            ($grid eq 'off')? ($out = " noxtics noytics"):
                ($out = " xtics ytics");
        }
        $out .= " mxtics mytics" if (defined $mgrid && $mgrid eq 'on');
    }
    return($out);
}


# Convert grid string to hash
# - called by _setGrid
sub _gridString2Hash
{
    my ($grid) = @_;
    return($grid) if (ref($grid) eq 'HASH');

    my %out;
    $out{xlines} = $out{ylines} = $out{zlines} = $grid;
    return(\%out);
}


# Set the details of the graph border and legend box border
# - called by _setChart()
#
# Usage example:
# border => {
#      linetype => 3,            # default: solid
#      width    => 2,            # default: 0
#      color    => '#ff00ff',    # default: system defined
#      layer    => 'back',       # default: front
# },
#
# Remark:
# - By default, the color of the axis tics would follow the border unless
#   specified otherwise.
sub _setBorder
{
    my ($border) = @_;

    my $out = '';
	$out .= " $$border{layer}" if (defined $$border{layer});
    $out .= " linetype ".&_lineType($$border{linetype}) if
        (defined $$border{linetype});
    $out .= " linecolor rgb \"$$border{color}\"" if (defined $$border{color});
    $out .= " linewidth $$border{width}" if (defined $$border{width});
    return($out);
}


# Format the legend (key)
#
# Usage example:
# legend => {
#    position => "outside bottom",
#    width    => 3,
#    height   => 4,
#    align    => "right",
#    order    => "horizontal reverse",
#    title    => "Title of the legend",
#    sample   => {
#        length   => 3,
#        position => "left",
#        spacing  => 2,
#    },
#    border   => {
#        linetype => 2,
#        width    => 1,
#        color    => "blue",
#    },
# },
sub _setLegend
{
    my ($legend) = @_;

    my $out = '';
    if (defined $$legend{position})
    {
        ($$legend{position} =~ /\d/)? ($out .= " at $$legend{position}"):
            ($out .= " $$legend{position}");
    }
    $out .= " width $$legend{width}" if (defined $$legend{width});
    $out .= " height $$legend{height}" if (defined $$legend{height});
    if (defined $$legend{align})
    {
        $out .= " Left" if ($$legend{align} eq 'left');
        $out .= " Right" if ($$legend{align} eq 'right');
    }
    if (defined $$legend{order})
    {
        my $order = $$legend{order};
        $order =~ s/reverse/invert/;
        $out .= " $order";
    }
    if (defined $$legend{title})
    {
        if (ref($$legend{title}) eq 'HASH')
        {
            my $title = $$legend{title};
            $out .= " title \"$$title{text}\"";
            $out .= " noenhanced" if (!defined $$title{enhanced} ||
                $$title{enhanced} ne 'on');
        }
        else
        {
            $out .= " title \"$$legend{title}\" noenhanced";
        }
    }
    if (defined $$legend{sample})
    {
        $out .= " samplen $$legend{sample}{length}" if
            (defined $$legend{sample}{length});
        $out .= " reverse" if (defined $$legend{sample}{position} ||
            $$legend{sample}{position} eq "left");
        $out .= " spacing $$legend{sample}{spacing}" if
            (defined $$legend{sample}{spacing});
    }
    if (defined $$legend{border})
    {
        if (ref($$legend{border}) eq 'HASH')
        {
            $out .= " box ".&_setBorder($$legend{border});
        }
        elsif ($$legend{border} eq "off")
        {
            $out .= " no box";
        }
        elsif ($$legend{border} eq "on")
        {
            $out .= " box";
        }
    }
    return($out);
}


# Set title and layout of the multiplot
sub _setMultiplot
{
    my ($self, $nrows, $ncols) = @_;

    open(PLT, ">>$self->{_script}") || confess("Can't write $self->{_script}");
    print PLT "set multiplot";
    print PLT " title \"$self->{title}\"" if (defined $self->{title});
    print PLT " layout $nrows, $ncols" if (defined $nrows);
    print PLT "\n";
    close(PLT);
}


# Usage example:
# timestamp => {
#    fmt    => '%d/%m/%y %H:%M',
#    offset => "10,-3"
#    font   => "Helvetica",
# },
# # OR
# timestamp => 'on';
sub _setTimestamp
{
    my ($ts) = @_;

    my $out = '';
    if (ref($ts) eq 'HASH')
    {
        $out .= " \"$$ts{fmt}\"" if (defined $$ts{fmt});
        $out .= " offset $$ts{offset}" if (defined $$ts{offset});
        $out .= " font \"$$ts{font}\"" if (defined $$ts{font});
    }
    elsif ($ts ne 'on')
    {
        return($ts);
    }
    return($out);
}


# Call Gnuplot to generate the image file
sub execute
{
    my ($self) = @_;

    # Try to find the executable of Gnuplot
    my $gnuplot = 'gnuplot';
    if (defined $self->{gnuplot})
    {
        $gnuplot = $self->{gnuplot};
    }

lib/Chart/Gnuplot.pm  view on Meta::CPAN

Label of the secondary x-axis (displayed on the top of the graph) and the
secondary y-axis (displayed on the right of the graph). See L<xlabel>.

=head3 xrange, yrange, zrange

Range of the x-axis, y-axis and z-axis in the plot, e.g.

    xrange => [0, "pi"]

would make the plot from x = 0 to x = 3.14159...

=head3 x2range, y2range

Range of the secondary (top horizontal and right vertical) axes of the plot.
See L<xrange, yrange, zrange>.

=head3 trange, urange, vrange

Range of the parametric parameter (t for 2D plots, while u and v for 3D plots).
See L<xrange, yrange, zrange>.

=head3 xtics, ytics, ztics

The tics and tic label on the x-axis, y-axis and z-axis. E.g.

   xtics => {
      labels   => [-10, 15, 20, 25],
      labelfmt => "%3f",
      ....
   }

If you set this to C<undef>. E.g.,

    xtics => undef

Then this option will be explicitly I<unset> and the chart will have not have
tic marks on the specified axis.

Supported properties are:

    labels    : the locations of the tic labels
    start     : the starting value for manually-specified range
	incr      : the increment for manually-specified range
	end       : the ending value for manually-specified range
    labelfmt  : format of the labels
    font      : font of the labels
    fontsize  : font size of the lebals
    fontcolor : font color of the label
    offset    : position of the tic labels shifted from its default
    rotate    : rotation of the tic labels
    length    : length of the tics
    along     : where the tics are put (axis/border)
    minor     : number of minor tics between adjacant major tics
    mirror    : turn on and off the tic label of the secondary axis. No effect
              : for C<ztics> (on/off)

=head3 x2tics, y2tics

The tics and tic label of the secondary axes. See L<xtics, ytics, ztics>.

=head3 legend

Legend describing the plots. Supported properties are:

    position : position of the legend
    width    : number of character widths to be added or subtracted to the
             : region of the legend
    height   : number of character heights to be added or subtracted to the
             : region of the legend
    align    : alignment of the text label. Left or right (default)
    order    : order of the keys
    title    : title of the legend
    sample   : format of the sample lines
    border   : border of the legend
    
See L<border> for the available options of border

E.g.

    legend => {
       position => "outside bottom",
       width    => 3,
       height   => 4,
       align    => "right",
       order    => "horizontal reverse",
       title    => "Title of the legend",
       sample   => {
           length   => 3,
           position => "left",
           spacing  => 2,
       },
       border   => {
           linetype => 2,
           width    => 1,
           color    => "blue",
       },
    }

=head3 timeaxis

Specify the axes of which the tic labels are date/time string. Possible values
are combinations of "x", "y", "x2", and "y2" joined by ",". E.g.

    timeaxis => "x, y2"

means that the x-axis and y2-axis are data/time axes.

=head3 border

Border of the graph. Properties supported are:

    sides    : sides on which border is displayed
    linetype : line type
    width    : line width
    color    : line coler

E.g.

    border => {
        sides    => "bottom, left",
        linetype => 3,
        width    => 2,
        color    => '#ff00ff',
    }

C<sides> tells which side(s) will be displayed. Default is all four borders for
2D plots, and four bottom and left vertial borders for 3D plots. Acceptable
valurs are the 12-bit code (see the Gnuplot manual) or the following names:

    bottom
    left
    top
    right
    bottom left front
    bottom left back
    bottom right front
    bottom right back
    left vertical
    right vertical
    front vertical
    back vertical
    top left front
    top left back
    top right front
    top right back

lib/Chart/Gnuplot.pm  view on Meta::CPAN

    gamma(x)     : gamma function
    ibeta(a,b,x) : incomplete beta function
    inverf(x)    : inverse error function
    igamma(a,x)  : incomplete gamma function
    imag(x)      : imaginary part
    invnorm(x)   : inverse normal distribution function
    int(x)       : integer part
    lambertw(x)  : Lambert W function
    lgamma(x)    : log gamma function
    log(x)       : natural logarithm
    log10(x)     : common logarithm
    norm(x)      : normal distribution function
    rand(x)      : pseudo random number
    real(x)      : real part
    sgn(x)       : sign function
    sin(x)       : sine
    sinh(x)      : hyperbolic sine
    sqrt(x)      : square root
    tan(x)       : tangent
    tanh(x)      : hyperbolic tangent

Please see the Gnuplot manual for updated information.

Supported mathematical constants:

    pi : the circular constant 3.14159...

Supported arithmetic operators:

    addition           : +
    division           : /
    exponentiation     : **
    factorial          : !
    modulo             : %
    multiplication     : *
    subtraction        : -, e.g., 1-2
    unary minus        : -, e.g., -1

Supported logical operations:

    and                      : &&
    complement               : ~
    equality                 : ==
    greater than             : >
    greater than or equal to : >=
    inequality               : !=
    less than                : <
    less than or equal to    : <= 
    negation                 : !
    or                       : ||
    if ... than else ...     : ?:, e.g., a ? b : c

Parametric functions may be represented as hash. E.g.

    func => {x => 'sin(t)', y => 'cos(t)'}

will draw a circle.

=head3 title

Title of the dataset (shown in the legend).

=head3 style

The plotting style for the dataset, including

    lines          : join adjacent points by straight lines
    points         : mark each points by a symbol
    linespoints    : both "lines" and "points"
    dots           : dot each points. Useful for large datasets
    impluses       : draw a vertical line from the x-axis to each point
    steps          : join adjacent points by steps
    boxes          : draw a centered box from the x-axis to each point
    xerrorbars     : "dots" with horizontal error bars
    yerrorbars     : "dots" with vertical error bars
    xyerrorbars    : both "xerrorbars" and "yerrorbars"
    xerrorlines    : "linespoints" with horizontal error bars
    yerrorlines    : "linespoints" with vertical error bars
    xyerrorlines   : both "xerrorlines" and "yerrorlines"
    boxerrorbars   : "boxes" with "yerrorbars"
    boxxyerrorbars : use rectangles to represent the data with errors
    financebars    : finance bars for open, high, low and close price
    candlesticks   : candle sticks for open, high, low and close price
    hbars          : horizontal bars (experimental)
    hlines         : horizontal lines (experimental)
    vectors        : arrows
    circles        : circles, for say, bubble charts
    histograms     : for plotting histograms

C<hbars> and C<hlines> are available only if the data is input from C<points>
or C<(x,y)data>.

=head3 color

Color of the dataset in the plot. Can be a named color or RBG (#RRGGBB) value.
The supported color names can be found in the file F<doc/colors.txt> in the
distribution. E.g.

    color => "#99ccff"

is equivalent to

    color => "dark-red"

=head3 width

Line width used in the plot. The default width is 1.

=head3 linetype

Line type. Can be an integer or line type name. The supported line type names
can be found in the file F<doc/linetypes.txt> in the distribution. E.g.

    linetype => 3

is equivalent to

    linetype => 'dash'

Note: the line type may not be displayed as the name if C<terminal> is set and
is not postscript.

lib/Chart/Gnuplot.pm  view on Meta::CPAN

=over

=item 1. Plot a mathematical expression

    my $chart = Chart::Gnuplot->new(
        output => "expression.png"
    );

    my $dataSet = Chart::Gnuplot::DataSet->new(
        func => "sin(x)"
    );

    $chart->plot2d($dataSet);

=item 2. Plot from two Perl arrays, one for the x-axis data and the other the
y-axis.

    my $chart = Chart::Gnuplot->new(
        output => "arrays.png"
    );

    my $dataSet = Chart::Gnuplot::DataSet->new(
        xdata => \@x,
        ydata => \@y,
    );

    $chart->plot2d($dataSet);

=item 3. Plot x-y pairs

    # Data
    my @xy = (
        [1.1, -3],
        [1.2, -2],
        [3.5,  0],
        ...
    );

    my $chart = Chart::Gnuplot->new(
        output => "points.png"
    );

    my $dataSet = Chart::Gnuplot::DataSet->new(
        points => \@xy
    );

    $chart->plot2d($dataSet);

=item 4. Plot data from a data file

    my $chart = Chart::Gnuplot->new(
        output => "file.png"
    );

    my $dataSet = Chart::Gnuplot::DataSet->new(
        datafile => "in.dat"
    );

    $chart->plot2d($dataSet);

=item 5. Chart title, axis label and legend

    # Chart object
    my $chart = Chart::Gnuplot->new(
        output => "trigonometric.gif",
        title  => "Three basic trigonometric functions",
        xlabel => "angle in radian",
        ylabel => "function value"
    );

    # Data set objects
    my $sine = Chart::Gnuplot::DataSet->new(
        func  => "sin(x)",
        title => "sine function"
    );
    my $cosine = Chart::Gnuplot::DataSet->new(
        func  => "cos(x)",
        title => "cosine function"
    );
    my $tangent = Chart::Gnuplot::DataSet->new(
        func  => "tan(x)",
        title => "tangent function"
    );

    $chart->plot2d($sine, $cosine, $tangent);

=item 6. Title in non-English characters (Thanks to WOLfgang Schricker)

    use Encode;

    my $title = ...   # Title with German umlauts
    $title = decode("utf8", $title);

    Chart::Gnuplot->new(
        encoding => 'iso-8859-1',
        title    => $title,
    );

=item 7. Plot a financial time series

    my $chart = Chart::Gnuplot->new(
        output   => "dj.ps",
        title    => "Dow-Jones Index time series",
        timeaxis => 'x',
        xtics    => {
            labelfmt => '%b%y',
        },
    );

    my $dow = Chart::Gnuplot::DataSet->new(
        file    => "dj.dat",
        timefmt => '%Y-%m-%d',      # time format of the input data
        style   => "candlesticks",
        grid    => 'on',
    );

    $chart->plot2d($dow);

=item 8. Plot several graphs on the same image

    my $chart = Chart::Gnuplot->new(



( run in 0.507 second using v1.01-cache-2.11-cpan-39bf76dae61 )