Chart::Gnuplot - Plot graph using Gnuplot on the fly
use Chart::Gnuplot; # Data my @x = (-10 .. 10); my @y = (0 .. 20); # Create chart object and specify the properties of the chart my $chart = Chart::Gnuplot->new( output => "fig/simple.png", title => "Simple testing", xlabel => "My x-axis label", ylabel => "My y-axis label", .... ); # Create dataset object and specify the properties of the dataset my $dataSet = Chart::Gnuplot::DataSet->new( xdata => \@x, ydata => \@y, title => "Plotting a line from Perl arrays", style => "linespoints", .... ); # Plot the data set on the chart $chart->plot2d($dataSet); ################################################## # Plot many data sets on a single chart $chart->plot2d($dataSet1, $dataSet2, ...);
This module is to plot graphs uning GNUPLOT on the fly. In order to use this module, gnuplot need to be installed. If image format other than PS, PDF and EPS is required to generate, the convert program of ImageMagick is also needed.
To plot chart using Chart::Gnuplot, a chart object and at least one dataset object are needed to be created. Information about the chart such as output file, chart title, axes labels and so on is specified in the chart object. Dataset object contains information about the dataset to be plotted, including source of the data points, dataset label, color used to plot and more.
After chart object and dataset object(s) are created, the chart can be plotted using the plot2d, plot3d or multiplot method of the chart object, e.g.
# $chart is the chart object $chart->plot2d($dataSet1, $dataSet2, ...);
To illustate the feature of Chart::Gnuplot, the best way is to show by examples.
The chart object can be initiated by the c<new> method. Properties of the chart may be specified optionally when the object is initiated:
my $chart = Chart::Gnuplot->new(%options);
Output file of the graph. By default, the image format is detected automatically by the extension of the filename. However, it can also be changed manually by using the format conversion methods such as convert and png (see sessions below).
convert
png
The supported image formats are:
bmp : Microsoft Windows bitmap epdf : Encapsulated Portable Document Format epi : Encapsulated PostScript Interchange format eps : Encapsulated PostScript gif : Graphics Interchange Format jpg : Joint Photographic Experts Group JFIF format pdf : Portable Document Format png : Portable Network Graphics ppm : Portable Pixmap Format ps : PostScript file psd : Adobe Photoshop bitmap file xpm : X Windows system pixmap
If the filename has no extension, postscipt will be used.
Title of the chart. E.g.,
title => "Chart title"
Properties of the chart title can be specified in hash. E.g.,
title => { text => "Chart title", font => "arial, 20", ..... }
Supported properties are:
text : title in plain text font : font face (and optionally font size) color : font color offset : offset relative to the default position enhanced : title contains subscript/superscipt/greek? (on/off)
Default values would be used for properties not specified. These properties has no effect on the main title of the multi-chart (see multiplot).
Label of the x-axis. E.g.
xlabel => "Bottom axis label"
Properties of the chart title can be specified in hash, similar to the chart title. Supported properties are:
text : title in plain text font : font face (and optionally font size) color : font color offset : offset relative to the default position rotate : rotation by degrees enhanced : title contains subscript/superscipt/greek? (on/off)
Label of the y-axis. See xlabel.
Label of the secondary x-axis (displayed on the top of the graph). See xlabel.
Label of the secondary y-axis (displayed on the right of the graph). See xlabel.
Label of the z-axis in 3D plots. See xlabel.
Range of the x-axis in the plot, e.g.
xrange => [0, "pi"];
Range of the y-axis in the plot.
Range of the secondary x-axis in the plot.
Range of the secondary y-axis in the plot.
Range of the z-axis in the 3D plot.
The tics and tic label of the x-axis.
The tics and tic label of the y-axis.
The tics and tic label of the x2-axis.
The tics and tic label of the y2-axis.
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.
Border of the graph. Properties supported are "linetype", "width", and "color". E.g.
border => { linetype => 3, width => 2, color => '#ff00ff', }
Grid lines.
Bottom margin (in character height). This option has no effect in 3D plots.
Left margin (in character width)
Right margin (in character width). This option has no effect in 3D plots.
Top margin (in character height). This option has no effect in 3D plots.
Orientation of the image. Possible values are "lanscape" and "portrait".
Size (length and height) of the image relative to the default.
Size of the chart relative to the chart size. This is useful in some multi-plot such as inset chart.
Origin of the chart. This is useful in some multi-plot such as inset chart.
Time stamp of the plot. To place the time stamp with default setting,
timestamp => 'on'
To set the format of the time stamp as well, e.g.,
timestamp => { fmt => '%d/%m/%y %H:%M', offset => "10,-3", font => "Helvetica", }
Background color of the chart. This option is experimental.
Background color of the plot area. This option has no effect in 3D plots and is experimental.
The path of Gnuplot installed. This option is useful if you have multiple versions of Gnuplot installed.
The terminal that Gnuplot use. The default terminal is "postscript". This attribute is not recommended to be changed unless you are familiar with the Gnuplot syntax. Please test carefully before using this in production code.
Terminal is not necessarily related to the output image format. You may convert the image format by the convert() method.
convert()
Constructor of the chart object. If no option is specified, default values would be used. See "Chart Options" for available options.
General set methods for arbitrary number of options.
$chart->set(%options);
$chart->plot2d(@dataSets);
Plot the data sets in a 2D chart. Each dataset is represented by a dataset object.
$chert->plot3d(@dataSets);
Plot the data sets in a 3D chart. Each dataset is represented by a dataset object. It is not yet completed. Only basic features are supported.
$chert->multiplot(@charts);
Plot multiple charts in the same image.
Add a 2D dataset to a chart without plotting it out immediately. Used with multiplot.
multiplot
Add a 3D dataset to a chart without plotting it out immediately. Used with multiplot.
Add an arbitrary text label. e.g.,
$chart->label( text => "This is a label", position => "0.2, 3 left", offset => "2,2", rotate => 45, font => "arial, 15", fontcolor => "dark-blue", pointtype => 3, pointsize => 5, pointcolor => "blue", );
$chart->convert($imageFmt);
Convert the image format to $imageFmt. See "Chart Options" for supported image formats.
$imageFmt
$chart->png;
Change the image format to PNG.
$chart->gif;
Change the image format to GIF.
$chart->jpg;
Change the image format to JPEG.
$chart->ps;
Change the image format to postscript.
$chart->pdf
Change the image format to PDF.
$chart->command($gnuplotCommand);
Add a gnuplot command. This method is useful for the Gnuplot features that have not yet implemented.
The dataset object can be initiated by the new method. Properties of the dataset may be specified optionally when the object is initiated:
new
my $dataset = Chart::Gnuplot::DataSet->new(%options);
The data source of the dataset can be specified by either one of the following ways:
The x values of the data points.
xdata => \@x
If xdata is omitted but ydata is defined, the integer index starting from 0 would be used for xdata.
xdata
ydata
The y values of the data points. See xdata.
The z values of the data points. See xdata
Data point matrix of the format [[x1,y1], [x2,y2], [x3,y3], ...]
points => \@points
Input data file
datafile => $file
The data files are assumed to be space-separated, with each row corresponding to one data point. Lines beginning with "#" are considered as comments and would be ignored. Other formats are not supported at this moment.
Mathematical function to be plotted. E.g.
func => "sin(x)*x**3"
Supported functions:
abs(x) : absolute value acos(x) : inverse cosine acosh(x) : inverse hyperbolic cosine arg(x) : complex argument asin(x) : inverse sine asinh(x) : inverse hyperbolic sine atan(x) : inverse tangent atanh(x) : inverse hyperbolic tangent besj0(x) : zeroth order Bessel function of the first kind besj1(x) : first order Bessel function of the first kind besy0(x) : zeroth order Bessel function of the second kind besy1(x) : first order Bessel function of the second kind ceil(x) : ceiling function cos(x) : cosine cosh(x) : hyperbolic cosine erf(x) : error function erfc(x) : complementary error function exp(x) : expontial function floor(x) : floor function 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
Title of the dataset (shown in the legend).
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
Color of the dataset in the plot. Can be a named color ot RBG (#RRGGBB) value. The supported color names can be found in the file doc/colors.txt in the distribution. E.g.
color => "#99ccff" # or color => "dark-red"
Line width used in the plot.
Line type.
Point type.
Point size of the plot.
Filling string. Has effect only on plotting styles "boxes", "boxxyerrorbars" and "financebars".
Axes used in the plot. Possible values are "x1y1", "x1y2", "x2y1" and "x2y2".
Time format of the input data. The valid format are:
%d : day of the month, 1-31 %m : month of the year, 1-12 %y : year, 2-digit, 0-99 %Y : year, 4-digit %j : day of the year, 1-365 %H : hour, 0-24 %M : minute, 0-60 %s : seconds since the Unix epoch (1970-01-01 00:00 UTC) %S : second, 0-60 %b : name of the month, 3-character abbreviation %B : name of the month
The smooth method used in plotting data points. Supported methods include cubic splines (csplines), Bezier curve (bezier) and other. Please see Gnuplot manual for details.
Constructor of the dataset object. If no option is specified, default values would be used. See "Dataset Options" for available options.
Some simple examples are shown below. Many more come with the distribution.
my $chart = Chart::Gnuplot->new( output => "expression.png" ); my $dataSet = Chart::Gnuplot::DataSet->new( func => "sin(x)" ); $chart->plot2d($dataSet);
my $chart = Chart::Gnuplot->new( output => "arrays.png" ); my $dataSet = Chart::Gnuplot::DataSet->new( xdata => \@x, ydata => \@y, ); $chart->plot2d($dataSet);
# 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);
my $chart = Chart::Gnuplot->new( output => "file.png" ); my $dataSet = Chart::Gnuplot::DataSet->new( file => "in.dat" ); $chart->plot2d($dataSet);
# 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);
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);
my $chart = Chart::Gnuplot->new( output => "multiplot.gif", ); my $left = Chart::Gnuplot->new(); my $sine = Chart::Gnuplot::DataSet->new( func => "sin(x)", ); $left->add2d($sine); my $center = Chart::Gnuplot->new(); my $cosine = Chart::Gnuplot::DataSet->new( func => "cos(x)", ); $center->add2d($cosine); my $right = Chart::Gnuplot->new(); my $tangent = Chart::Gnuplot::DataSet->new( func => "tan(x)", ); $right->add2d($tangent); # Place the Chart::Gnuplot objects in matrix to indicate their locations $chart->multiplot([ [$left, $center, $right] ]);
File::Copy, File::Temp
This version is tested against Gnuplot 4.2 patchlevel 0 and patchlevel 2 in Linux.
Gnuplot official website http://www.gnuplot.info
Chart::Graph::Gnuplot
Ka-Wai Mak <kwmak@cpan.org>
Copyright (c) 2008 Ka-Wai Mak. All rights reserved.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
To install Chart::Gnuplot, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Chart::Gnuplot
CPAN shell
perl -MCPAN -e shell install Chart::Gnuplot
For more information on module installation, please visit the detailed CPAN module installation guide.