Skip to content


Subversion checkout URL

You can clone with
Download ZIP
Gnuplot-based plotting backend for PDL
Pull request Compare This branch is 21 commits ahead, 34 commits behind master.
Fetching latest commit...
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.



This is a Gnuplot-based plotter for PDL. This repository stores the history for the PDL::Graphics::Gnuplot module on CPAN. Install the module via CPAN. CPAN page at


PDL::Graphics::Gnuplot - Gnuplot-based plotting for PDL


 pdl> use PDL::Graphics::Gnuplot;

 pdl> $x = sequence(101) - 50;
 pdl> gplot($x**2);

 pdl> gplot( {title => 'Parabola with error bars'},
       with => 'xyerrorbars', legend => 'Parabola',
       $x**2 * 10, abs($x)/10, abs($x)*5 );

 pdl> $xy = zeros(21,21)->ndcoords - pdl(10,10);
 pdl> $z = inner($xy, $xy);
 pdl> gplot({title  => 'Heat map', '3d' => 1,
        extracmds => 'set view 0,0'},
        with => 'image', $z*2);

 pdl> $w = gpwin();
 pdl> $pi    = 3.14159;
 pdl> $theta = zeros(200)->xlinvals(0, 6*$pi);
 pdl> $z     = zeros(200)->xlinvals(0, 5);
 pdl> $w->plot3d(cos($theta), sin($theta), $z);


This module allows PDL data to be plotted using Gnuplot as a backend for 2D and 3D plotting and image display. Gnuplot (not affiliated with the Gnu project) is a venerable, open-source plotting package that produces both interactive and publication-quality plots on a very wide variety of output devices. Gnuplot is a standalone package that must be obtained separately from this interface module. It is available through most Linux repositories, on MacOS via fink and MacPorts, and from its website

It is not necessary to understand the gnuplot syntax to generate basic, or even complex, plots - though the full syntax is available for advanced users who want to take advantage of the full flexibility of the Gnuplot backend.

The main subroutine that PDL::Graphics::Gnuplot exports by default is gplot(), which produces one or more overlain plots and/or images in a single plotting window. Depending on options, gplot() can produce line plots, scatterplots, error boxes, "candlesticks", images, or any overlain combination of these elements; or perspective views of 3-D renderings such as surface plots.

A call to gplot() looks like:

 gplot({temp_plot_options}, # optional hash or array ref
      curve_options, data, data, ... ,
      curve_options, data, data, ... );

PDL::Graphics::Gnuplot also implements an object oriented interface. Plot objects track individual gnuplot subprocesses. Direct calls to gplot() are tracked through a global object that stores globally set configuration variables.

Gnuplot collects two kinds of options hash: plot options, which describe the overall structure of the plot being produced (e.g. axis specifications, window size, and title), from curve options, which describe the behavior of individual traces or collections of points being plotted. In addition, the module itself supports options that allow direct pass-through of plotting commands to the underlying gnuplot process.

Basic plotting

Gnuplot generates many kinds of plot, from basic line plots and histograms to scaled labels. Individual plots can be 2-D or 3-D, and different sets of plot styles are supported in each mode. Plots can be sent to a variety of devices; see the description of plot options, below.

You select a plot style with the "with" curve option, as in

 $x = xvals(51)-25; $y = $x**2;
 gplot(with=>'points', $x, $y);  # Draw points on a parabola
 gplot(with=>'lines', $x, $y);   # Draw a parabola
 gplot({title=>"Parabolic fit"},
       with=>"yerrorbars", legend=>"data", $x, $y+(random($y)-0.5)*2*$y/20, pdl($y/20),
       with=>"lines",      legend=>"fit",  $x, $y);

Normal threading rules apply across the arguments to a given plot.

At least the first data column in a tuple is required to be a PDL. Subsequent data columns can be delivered as string data if desired, in a Perl list ref. If you use a list ref as a data column, then normal threading is disabled and all arguments must be 1-D and contain the same number of elements. For example:

 $x = xvals(5);
 $y = xvals(5)**2;
 $labels = ['one','two','three','four','five'];

See below for supported plot styles.

Options arguments

The plot options are parameters that affect the whole plot, like the title of the plot, the axis labels, the extents, 2d/3d selection, etc. All the plot options are described below in "Plot options".

The curve options are parameters that affect only one curve in particular. Each call to plot() can contain many curves, and options for a particular curve precede the data for that curve in the argument list. Furthermore, curve options are all cumulative. So if you set a particular style for a curve, this style will persist for all the following curves, until this style is turned off. The only exception to this is the legend option, since it's very rarely a good idea to have multiple curves with the same label. An example:

 gplot( with => 'points', $x, $a,
        y2   => 1,        $x, $b,
        with => 'lines',  $x, $c );

This plots 3 curves: $a vs. $x plotted with points on the main y-axis (this is the default), $b vs. $x plotted with points on the secondary y axis, and $c vs. $x plotted with lines also on the secondary y axis. All the curve options are described below in "Curve options".

Data arguments

Following the curve options in the plot() argument list is the actual data being plotted. Each output data point is a "tuple" whose size varies depending on what is being plotted. For example if we're making a simple 2D x-y plot, each tuple has 2 values; if we're making a 3d plot with each point having variable size and color, each tuple has 5 values (x,y,z,size,color). Each tuple element must be passed separately. For ordinary (non-curve) plots, the 0 dim of the tuple elements runs across plotted point. PDL threading is active, so multiple curves with similar curve options can be plotted by stacking data inside the passed-in piddles.

An example:

 my $pi    = 3.14159;
 my $theta = xvals(201) * 6 * $pi / 200;
 my $z     = xvals(201) * 5 / 200;

 plot( {'3d' => 1, title => 'double helix'},
       { with => 'linespoints pointsize variable pointtype 2 palette',
         legend => ['spiral 1','spiral 2'] },
         pdl( cos($theta), -cos($theta) ),       # x
         pdl( sin($theta), -sin($theta) ),       # y
         $z,                                     # z
         (0.5 + abs(cos($theta))),               # pointsize
         sin($theta/3)                           # color

This is a 3d plot with variable size and color. There are 5 values in the tuple, which we specify. The first 2 piddles have dimensions (N,2); all the other piddles have a single dimension. Thus the PDL threading generates 2 distinct curves, with varying values for x,y and identical values for everything else. To label the curves differently, 2 different sets of curve options are given. Since the curve options are cumulative, the style and tuplesize needs only to be passed in for the first curve; the second curve inherits those options.

Implicit domains

When making a simple 2D plot, if exactly 1 dimension is missing, PDL::Graphics::Gnuplot will use sequence(N) as the domain. This is why code like plot(pdl(1,5,3,4,4) ) works. Only one piddle is given here, but a default tuplesize of 2 is active, and we are thus exactly 1 piddle short. This is thus equivalent to plot( sequence(5), pdl(1,5,3,4,4) ).

If plotting in 3d or displaying an image, an implicit domain will be used if we are exactly 2 piddles short. In this case, PDL::Graphics::Gnuplot will use a 2D grid as a domain. Example:

 my $xy = zeros(21,21)->ndcoords - pdl(10,10);
 plot({'3d' => 1},
       with => 'points', inner($xy, $xy));
 plot( with => 'image',  sin(rvals(51,51)) );

Here the only given piddle has dimensions (21,21). This is a 3D plot, so we are exactly 2 piddles short. Thus, PDL::Graphics::Gnuplot generates an implicit domain, corresponding to a 21-by-21 grid.

One thing to watch out for it to make sure PDL::Graphics::Gnuplot doesn't get confused about when to use implicit domains. For example, plot($a,$b) is interpreted as plotting $b vs $a, not $a vs an implicit domain and $b vs an implicit domain. If 2 implicit plots are desired, add a separator: plot($a,{},$b). Here {} is an empty curve options hash. If $a and $b have the same dimensions, one can also do plot($a->cat($b)), taking advantage of PDL threading.


PDL::Graphics::Gnuplot supports image plotting in three styles via the "with" curve option.

The "image" style accepts a single image plane and displays it using the palette (pseudocolor map) that is specified in the plot options for that plot. As a special case, if you supply as data a (WxHx3) PDL it is treated as an RGB image and displayed with the "rgbimage" style (below). For quick image display there is also an "image" method:

 use PDL::Graphics::Gnuplot qw/image/;
 $im = sin(rvals(51,51)/2);
 image( $im );                # display the image
 gplot( with=>'image', $im );  # display the image (longer form)

The colors are autoscaled in both cases. To set a particular color range, use the 'cbrange' plot option:

 image( {cbrange=>[0,1]}, $im );

You can plot rgb images directly with the image style, just by including a 3rd dimension of size 3 on your image:

 $rgbim = pdl( xvals($im), yvals($im),rvals($im)/sqrt(2));
 image( $rgbim );                # display an RGB image
 image( with=>'image', $rgbim ); # display an RGB image (longer form)

Some additional plot styles exist to specify RGB and RGB transparent forms directly. These are the "with" styles "rgbimage" and "rgbalpha". For each of them you must specify the channels as separate PDLs:

 plot( with=>'rgbimage', $rgbim->dog );           # RGB  the long way
 plot( with=>'rgbalpha', $rgbim->dog, ($im>0) );  # RGBA the long way 

According to the gnuplot specification you can also give X and Y values for each pixel, as in

 plot( with=>'image', xvals($im), yvals($im), $im )

but this appears not to work properly for anything more complicated than a trivial matrix of X and Y values.


The graphical backends of Gnuplot are interactive, allowing the user to pan, zoom, rotate and measure the data in the plot window. See the Gnuplot documentation for details about how to do this. Some terminals (such as wxt) are persistently interactive, and the rest of this section does not apply to them. Other terminals (such as x11) maintain their interactivity only while the underlying gnuplot process is active -- i.e. until another plot is created with the same PDL::Graphics::Gnuplot object, or until the perl process exits (whichever comes first).


Gnuplot controls plot style with "plot options" that configure and specify virtually all aspects of the plot to be produced. Plot options are tracked as stored state in the PDL::Graphics::Gnuplot object. You can set them by passing them in to the constructor, to an options method, or to the plot method itself.

Nearly all the underlying Gnuplot plot options are supported, as well as some additional options that are parsed by the module itself for convenience.

POs for Output: terminal, termoption, output, device, hardcopy

terminal sets the output device type for Gnuplot, and output sets the actual output file or window number.

device and hardcopy are for convenience. device offers a PGPLOT-style device specifier in "filename/device" format (the "filename" gets sent to the "output" option, the "device" gets sent to the "terminal" option). hardcopy takes an output file name and attempts to parse out a file suffix and infer a device type.

For finer grained control of the plotting environment, you can send "terminal options" to Gnuplot. If you set the terminal directly with plot options, you can include terminal options by interpolating them into a string, as in terminal jpeg interlace butt crop, or you can use the constructor new (also exported as gpwin), which parses terminal options as an argument list.

The routine PDL::Graphics::Gnuplot::terminfo prints a list of all availale terminals or, if you pass in a terminal name, options accepted by that terminal.

POs for Titles: title, (x|x2|y|y2|z|cb)label, key

Gnuplot supports "enhanced" text escapes on most terminals; see "text", below.

The title option lets you set a title for the whole plot.

Individual plot components are labeled with the label options. xlabel, x2label, ylabel, and y2label specify axis titles for 2-D plots. The zlabel works for 3-D plots. The cblabel option sets the label for the color box, in plot types that have one (e.g. image display).

(Don't be confused by clabel, which doesnt' set a label at all, rather specifies the printf format used by contour labels in contour plots.)

key controls where the plot key (that relates line/symbol style to label) is placed on the plot. It takes a scalar boolean indicating whether to turn the key on (with default values) or off, or a list ref containing any of the following arguments (all are optional) in the order listed:

( on | off ) - turn the key on or off
( inside | outside | lmargin | rmargin | tmargin | bmargin | at <pos> )

These keywords set the location of the key -- "inside/outside" is relative to the plot border; the margin keywords indicate location in the margins of the plot; and at <pos> (where <pos> is a 2-list containing (x,y): key=[at=>[0.5,0.5]]>) is an exact location to place the key.

( left | right | center ) ( top | bottom | center ) - horiz./vert. alignment
( vertical | horizontal ) - stacking direction within the key
( Left | Right ) - justification of plot labels within the key (note case)
[no]reverse - switch order of label and sample line
[no]invert - invert the stack order of the labels
samplen <length> - set the length of the sample lines
spacing <dist> - set the spacing between adjacent labels in the list
[no]autotitle - control whether labels are generated when not specified
title "<text>" - set a title for the key
[no]enhanced - override terminal settings for enhanced text interpretation
font "<face>,<size>" - set font for the labels
textcolor <colorspec>
[no]box linestyle <ls> linetype <lt> linewidth <lw> - control box around the key

POs for axes, grids, & borders: grid, (x|x2|y|y2|z)zeroaxis, border

Normally, tick marks and labels are applied to the border of a plot, and no extra axes (e.g. the y=0 line) nor coordinate grids are shown. You can specify which (if any) zero axes should be drawn, and which (if any) borders should be drawn.

The border option controls whether the plot itself has a border drawn around it. You can feed it a scalar boolean value to indicate whether borders should be drawn around the plot -- or you can feed in a list ref containing options. The options are all optional but must be supplied in the order given.

<integer> - packed bit flags for which border lines to draw

The default if you set a true value for border is to draw all border lines. You can feed in a single integer value containing a bit mask, to draw only some border lines. From LSB to MSB, the coded lines are bottom, left, top, right for 2D plots -- e.g. 5 will draw bottom and top borders but neither left nor right.

In three dimensions, 12 bits are used to describe the twelve edges of a cube surrounding the plot. In groups of three, the first four control the bottom (xy) plane edges in the same order as in the 2-D plots; the middle four control the vertical edges that rise from the clockwise end of the bottom plane edges; and the last four control the top plane edges.

( back | front ) - draw borders first or last (controls hidden line appearance)
linewidth <lw>, linestyle <ls>, linetype <lt>

These are Gnuplot's usual three options for line control.

To draw each axis set the appropriate "zeroaxis" parameter -- i.e. to draw the X axis (y=0), use xzeroaxis=1>. If you just want the axis turned on with default values, you can feed in a Boolean scalar; if you want to set its parameters, you can feed in a list ref containing linewidth, linestyle, and linetype (with appropriate parameters for each), e.g. xzeroaxis=[linewidth=>2]>.

To draw a coordinate grid with default values, set grid=1>. For more control, feed in a list ref with zero or more of the following parameters, in order:

tics specifications

These keywords indicate whether gridlines should be drawn on axis tics (see below) for each axis. Each one takes the form of either "no" or "m" or "", followed by an axis name and "tics" -- e.g. grid=["noxtics","ymtics"]> draws no X gridlines and draws (horizontal) Y gridlines on Y axis major and minor tics, while grid=["xtics","ytics"]> or grid=["xtics ytics"]> will draw both vertical (X) and horizontal (Y) grid lines on major tics.

POs for axis ranging: (x|x2|y|y2|z|r|cb|t|u|v)range, autoscale, logscale

Gnuplot accepts explicit ranges as plot options for all axes. Each option accepts a list ref with (min, max). If either min or max is missing, then the opposite limit is autoscaled. The x and y ranges refer to the usual ordinate and abscissa of the plot; x2 and y2 refer to alternate ordinate and abscissa; z if for 3-D plots; r is for polar plots; t, u, and v are for parametric plots. cb is for the color box on plots that include it (see "color", below).

rrange is used for radial coordinates (which are accessible using the mapping plot option, below).

cbrange (for 'color box range') sets the range of values over which palette colors (either gray or pseudocolor) are matched. It is valid in any color-mapped plot (including images or palette-mapped lines or points), even if no color box is being displayed for this plot.

trange, urange, and vrange set ranges for the parametric coordinates if you are plotting a parametric curve.

By default all axes are autoscaled unless you specify a range on that axis, and partially (min or max) autoscaled if you specify a partial range on that axis. autoscale allows more explicit control of how autoscaling is performed, on an axis-by-axis basis. It accepts a list ref, each element of which specifies how a single axis should be autoscaled. Each element contains an axis name followed by one of "fix,"min","max","fixmin", or "fixmax", e.g.


To not autoscale an axis at all, specify a range for it. The fix style of autoscaling forces the autoscaler to use the actual min/max of the data as the limit for the corresponding axis -- by default the axis gets extended to the next minor tic (as set by the autoticker or by a tic specification, see below).

logscale allows you to turn on logarithmic scaling for any or all axes, and to set the base of the logarithm. It takes a list ref, the first element of which is a string mushing together the names of all the axes to scale logarithmically, and the second of which is the base of the logarithm: logscale=[xy=>10]>. You can also leave off the base if you want base-10 logs: logscale=['xy']>.

POs for Axis tick marks - [m](x|x2|y|y2|z|cb)tics

Label tick marks are called "tics" within Gnuplot, and they are extensively controllable via the "<axis>tics" options. In particular, major and minor ticks are supported, as are arbitrarily variable length ticks, non-equally spaced ticks, and arbitrarily labelled ticks. Support exists for time formatted ticks (see "Time data" below).

By default, gnuplot will automatically place major and minor ticks. You can turn off ticks on an axis by setting the appropriate <foo>tics option to a defined, false scalar value (e.g. xtics=0>), and turn them on with default values by setting the option to a true scalar value (e.g. xtics=1>).

If you prepend an 'm' to any tics option, it affects minor tics instead of major tics (major tics typically show units; minor tics typically show fractions of a unit).

Each tics option can accept a list ref containing options to pass directly to Gnuplot (they are not parsed further -- though a future version of PDL::Graphics::Gnuplot may accept a hash ref and parse it into an options string). You can interpolate all the words into a single string, provided it is contained in a list ref. The keywords are all optional, but must appear in the order given here, and may not be abbreviated. They are:

  • ( axis | border ) - are tics on the axis, or on the plot border?
  • ( nomirror | mirror ) - place mirrored tics on the opposite axis/border?
  • ( in | out ) - controls tic direction relative to the plot
  • scale ( default | <major>[,<minor>] ) - multiplier on tic length
  • ( norotate | rotate [by <ang>] ) - turn label text by 90deg or specified angle
  • ( nooffset | offset <x>,<y>[,<z>] ) - offset label text from default position
  • (autofreq | <incr> | <start>,<incr>[,<end>] | <label-list>) - set tic locations
  • format "<formatstring>" - printf-style formatting for tic labels
  • font "<font>[,<size>]" - set font name and size (system font name)
  • rangelimited - limit tics to the range of values actually present in the plot
  • textcolor <colorspec> - set the color of the ticks (see "color specs" below)

For example, to turn on inward mirrored X axis ticks with diagonal Arial 9 text, use:

 xtics => ['axis','mirror','in','rotate by 45','font "Arial,9"']

POs for Time/date values - (x|x2|y|y2|z|cb)(m|d)tics, (x|x2|y|y2|z|cb)data

Gnuplot contains support for plotting time, date, or elapsed time on any of its axes. There are three main methods, which are mutually exclusive (i.e. you should not attempt to use two at once on the same axis).

Plotting timestamps using UNIX times

You can set any axis to plot timestamps rather than numeric values by setting the corresponding "data" plot option to "time", e.g. xdata="time">. If you do so, then numeric values in the corresponding data are interpreted as UNIX times (seconds since the UNIX epoch). No provision is made for UTC->TAI conversion (yet). You can format how the times are plotted with the "format" option in the various "tics" options(above). Output specifiers should be in UNIX strftime(3) format -- for example,

 xdata=>"time",xtics=>['format "%G-%m-%dT%H:%M:%S"']

will plot UNIX times as ISO timestamps in the ordinate.

day-of-week plotting

If you just want to plot named days of the week, you can instead use the dtics options set plotting to day of week, where 0 is Sunday and 6 is Saturday; values are interpreted modulo 7. For example, xmtics=1,xrange=>[-4,9]> will plot two weeks from Wednesday to Wednesday.

month-of-year plotting

The mtics options set plotting to months of the year, where 1 is January and 12 is December, so xdtics=1, xrange=>[0,4]> will include Christmas through Easter.

POs for location/size - (t|b|l|r)margin, offsets, origin, size, justify, clip

Adjusting the size, location, and margins of the plot on the plotting surface is something of a null operation for most single plots -- but you can tweak the placement and size of the plot with these options. That is particularly useful for multiplots, where you might like to make an inset plot or to lay out a set of plots in a custom way.

The margin options accept scalar values -- either a positive number of character heights or widths of margin around the plot compared to the edge of the device window, or a string that starts with "at screen " and interpolates a number containing the fraction of the plot window offset. The "at screen" technique allows exact plot placement and is an alternative to the origin and size options below.

The offsets option allows you to put an empty boundary around the data, inside the plot borders, in an autosacaled graph. The offsets only affect the x1 and y1 axes, and only in 2D plot commands. offsets accepts a list ref with four values for the offsets, which are given in scientific (plotted) axis units.

The origin option lets you specify the origin (lower left corner) of an individual plot on the plotting window. The coordinates are screen coordinates -- i.e. fraction of the total plotting window.

The size option lets you adjust the size and aspect ratio of the plot, as an absolute fraction of the plot window size. You feed in fractional ratios, as in size=[$xfrac, $yfrac]>. You can also feed in some keywords to adjust the aspect ratio of the plot. The size option overrides any autoscaling that is done by the auto-layout in multiplot mode, so use with caution -- particularly if you are multiplotting. You can use "size" to adjust the aspect ratio of a plot, but this is deprecated in favor of the pseudo-option justify.

justify sets the scientific aspect ratio of a 2-D plot. Unity yields a plot with a square scientific aspect ratio. Larger numbers yield taller plots.

clip controls the border between the plotted data and the border of the plot. There are three clip types supported: points, one, and two. You can set them independently by passing in booleans with their names: clip=[points=>1,two=>0]>.

POs for Color: colorbox, palette, clut

Color plots are supported via RGB and pseudocolor. Plots that use pseudcolor or grayscale can have a "color box" that shows the photometric meaning of the color.

The colorbox generally appears when necessary but can be controlled manually with the colorbox option. colorbox accepts a scalar boolean value indicating whether or no to draw a color box, or a list ref containing additional options. The options are all, well, optional but must appear in the order given:

( vertical | horizontal ) - indicates direction of the gradient in the box
( default | user ) - indicates user origin and size

If you specify default the colorbox will be placed on the right-hand side of the plot; if you specify user, you give the location and size in subsequent arguments:

 colorbox => [ 'user', 'origin'=>"$x,$y", 'size' => "$x,$y" ]
( front | back ) - draws the colorbox before or after the plot
( noborder | bdefault | border <line style> ) - specify border

The line style is a numeric type as described in the gnuplot manual.

The palette option offers many arguments that are not fully documented in this version but are explained in the gnuplot manual. It offers complete control over the pseudocolor mapping function.

For simple color maps, clut gives access to a set of named color maps. (from "Color Look Up Table"). A few existing color maps are: "default", "gray", "sepia", "ocean", "rainbow", "heat1", "heat2", and "wheel". To see a complete list, specify an invalid table, e.g. "clut=>'xxx'". (This should be improved in a future version).

POs for 3D: trid, view, pm3d, hidden3d, dgrid3d, surface, xyplane, mapping

If trid or its synonym 3d is true, Gnuplot renders a 3-D plot. This changes the default tuple size from 2 to 3. This option is used to switch between the Gnuplot "plot" and "splot" command, but it is tracked with persistent state just as any other option.

The view option controls the viewpoint of the 3-D plot. It takes a list of numbers: view=[$rot_x, $rot_z, $scale, $scale_z]>. After each number, you can omit the subsequent ones. Alternatively, view=['map']> represents the drawing as a map (e.g. for contour plots) and view=[equal=>'xy']> forces equal length scales on the X and Y axes regardless of perspective, while view=[equal=>'xyz']> sets equal length scales on all three axes.

The pm3d option accepts several parameters to control the pm3d plot style, which is a palette-mapped 3d surface. They are not documented here in this version of the module but are explained in the gnuplot manual.

hidden3d accepts a list of parameters to control how hidden surfaces are plotted (or not) in 3D. It accepts a boolean argument indicating whether to hide "hidden" surfaces and lines; or a list ref containing parameters that control how hidden surfaces and lines are handled. For details see the gnuplot manual.

xyplane sets the location of that plane (which is drawn) relative to the rest of the plot in 3-space. It takes a single string: "at" or "relative", and a number. xyplane=[at=>$z]> places the XY plane at the stated Z value (in scientific units) on the plot. xyplane=[relative=>$frac]> places the XY plane $frac times the length of the scaled Z axis *below* the Z axis (i.e. 0 places it at the bottom of the plotted Z axis; and -1 places it at the top of the plotted Z axis).

mapping takes a single string: "cartesian", "spherical", or "cylindrical". It determines the interpretation of data coordinates in 3-space. (Compare to the polar option in 2-D).

POs for Contour plots - contour, cntrparam

Contour plots are only implemented in 3D. To make a normal 2D contour plot, use 3-D mode, but set the view to "map" - which projects the 3-D plot onto its 2-D XY plane. (This is convoluted, for sure -- future versions of this module may have a cleaner way to do it).

contour enables contour drawing on surfaces in 3D. It takes a single string, which should be "base", "surface", or "both".

cntrparam manages how contours are generated and smoothed. It accepts a list ref with a collection of Gnuplot parameters that are issued one per line; refer to the Gnuplot manual for how to operate it.

POs for Polar plots - polar, angles, mapping

You can make 2-D polar plots by setting polar to a true value. The ordinate is then plotted as angle, and the abscissa is radius on the plot. The ordinate can be in either radians or degrees, depending on the angles parameter

angles takes either "degrees" or "radians" (default is radians).

mapping is used to set 3-D polar plots, either cylindrical or spherical (see the section on 3-D plotting, above).

POs for Markup - label, arrow, object

You specify plot markup in advance of the plot command, with plot options. The options give you access to a collection of (separately) numbered descriptions that are accumulated into the plot object. To add a markup object to the next plot, supply the appropriate options as a list ref or as a single string. To specify all markup objects at once, supply the appropriate options for all of them as a nested list-of-lists.

To modify an object, you can specify it by number, either by appending the number to the plot option name (e.g. arrow3) or by supplying it as the first element of the option list for that object.

To remove all objects of a given type, supply undef (e.g. arrow=undef>).

For example, to place two labels, use the plot option:

 label => [["Upper left",at=>"10,10"],["lower right",at=>"20,5"]];

To add a label to an existing plot object, if you don't care about what index number it gets, do this:

 $w->options( label=>["my new label",at=>"10,20"] );

If you do care what index number it gets (or want to replace an existing label), do this:

 $w->options( label=>[$n, "my replacement label", at=>"10,20"] );

where $w is a Gnuplot object and $n contains the label number you care about.

label - add a text label to the plot.

The label option allows adding small bits of text at arbitrary locations on the plot.

Each label specifier list ref accepts the following suboptions, in order. All of them are optional -- if no options other than the index tag are given, then any existing label with that index is deleted.

For examples, please refer to the Gnuplot 4.4 manual, p. 117.

<tag> - optional index number (integer)
<label text> - text to place on the plot.

You may supply double-quotes inside the string, but it is not necessary in most cases (only if the string contains just an integer and you are not specifying a <tag>.

at <position> - where to place the text (sci. coordinates)

The <position> should be a string containing a gnuplot position specifier. At its simplest, the position is just two numbers separated by a comma, as in label2=["foo",at=>"5,3">, to specify (X,Y) location on the plot in scientific coordinates. Each number can be preceded by a coordinate system specifier; see the Gnuplot 4.4 manual (page 20) for details.

( left | center | right ) - text placement rel. to position
rotate [ by <degrees> ] - text rotation

If "rotate" appears in the list alone, then the label is rotated 90 degrees CCW (bottom-to-top instead of left-to-right). The following "by" clause is optional.

font "<name>,<size>" - font specifier

The <name>,<size> must be double quoted in the string (this may be fixed in a future version), as in

noenhanced - turn off gnuplot enhanced text processing (if enabled)
( front | back ) - rendering order (last or first)
textcolor <colorspec>
(point <pointstyle> | nopoint ) - control whether the exact position is marked
offset <offset> - offfset from position (in points).

arrow - place an arrow or callout line on the plot

Works similarly to the label option, but with an arrow instead of text.

The arguments, all of which are optional but which must be given in the order listed, are:

from <position> - start of arrow line

The <position> should be a string containing a gnuplot position specifier. At its simplest, the position is just two numbers separated by a comma, as in label2=["foo",at=>"5,3">, to specify (X,Y) location on the plot in scientific coordinates. Each number can be preceded by a coordinate system specifier; see the Gnuplot 4.4 manual (page 20) for details.

( to | rto ) <position> - end of arrow line

These work like from. For absolute placement, use "to". For placement relative to the from position, use "rto".

(arrowstyle | as) <arrow_style>

This specifies that the arrow be drawn in a particualr predeclared numerical style. If you give this parameter, you shoudl omit all the following ones.

( nohead | head | backhead | heads ) - specify arrowhead placement
size <length>,<angle>,<backangle> - specify arrowhead geometry
( filled | empty | nofilled ) - specify arrowhead fill
( front | back ) - specify drawing order ( last | first )
linestyle <line_style> - specify a numeric linestyle
linetype <line_type> - specify numeric line type
linewidth <line_width> - multiplier on the width of the line

object - place a shape on the graph

objects are rectangles, ellipses, circles, or polygons that can be placed arbitrarily on the plotting plane.

The arguments, all of which are optional but which must be given in the order listed, are:

<object-type> <object-properties> - type name of the shape and its type-specific properties

The <object-type> is one of four words: "rectangle", "ellipse", "circle", or "polygon".

You can specify a rectangle with from=$pos1, [r]to=>$pos2>, with center=$pos1, size=>"$w,$h">, or with at=$pos1,size=>"$w,$h">.

You can specify an ellipse with at=$pos, size=>"$w,$h"> or center=$pos size=>"$w,$h">, followed by angle=$a>.

You can specify a circle with at=$pos, size=>"$w,$h"> or center=$pos size=>"$w,$h">, followed by size=$radius> and (optionally) arc="[$begin:$end]">.

You can specify a polygon with from=$pos1,to=>$pos2,to=>$pos3,>$posn> or with from=$pos1,rto=>$diff1,rto=>$diff2,...rto=>$diffn>.

( front | back | behind ) - draw the object last | first | really-first.
fc <colorspec> - specify fill color
fs <fillstyle> - specify fill style
lw <width> - multiplier on line width

POs for appearance tweaks - bars, boxwidth, isosamples, pointsize, style

TBD - more to come.

POs for locale/internationalization - locale, decimalsign

locale is used to control date stamp creation. See the gnuplot manual.

decimalsign accepts a character to use in lieu of a "." for the decimalsign. (e.g. in European countries use decimalsign=','>).

PO Miscellany: globalwith, timestamp, zero, fontpath

globalwith is used as a default plot style if no valid 'with' curve option is present for a given curve.

If set to a nonzero value, timestamp causes a time stamp to be placed on the side of the plot, e.g. for keeping track of drafts.

zero sets the approximation threshold for zero values within gnuplot. Its default is 1e-8.

fontpath sets a font search path for gnuplot. It accepts a collection of file names as a list ref.

Advanced Gnuplot tweaks: topcmds, extracmds, bottomcmds, binary, dump, log

Plotting is carried out by sending a collection of commands to an underlying gnuplot process. In general, the plot options cause "set" commands to be sent, configuring gnuplot to make the plot; these are followed by a "plot" or "splot" command and by any cleanup that is necessary to keep gnuplot in a known state.

Provisions exist for sending commands directly to Gnuplot as part of a plot. You can send commands at the top of the configuration but just under the initial "set terminal" and "set output" commands (with the topcmds option), at the bottom of the configuration and just before the "plot" command (with the extracmds option), or after the plot command (with the bottomcmds option). Each of these plot options takes a list ref, each element of which should be one command line for gnuplot.

Most plotting is done with binary data transfer to Gnuplot; however, due to some bugs in Gnuplot binary handling, certain types of plot data are sent in ASCII. In particular, time series and label data require transmission in ASCII (as of Gnuplot 4.4). You can force ASCII transmission of all but image data by explicitly setting the binary=0> option.

dump is used for debugging. If true, it writes out the gnuplot commands to STDOUT instead of writing to a gnuplot process. Useful to see what commands would be sent to gnuplot. This is a dry run. Note that this dump will contain binary data, if the 'binary' option is given (see below)


Used for debugging. If true, writes out the gnuplot commands to STDERR in addition to writing to a gnuplot process. This is not a dry run: data is sent to gnuplot and to the log. Useful for debugging I/O issues. Note that this log will contain binary data, if the 'binary' option is given (see below)


The curve options describe details of specific curves within a plot. They are in a hash, whose keys are as follows:


Specifies the legend label for this curve


Specifies the style for this curve. The value is passed to gnuplot using its 'with' keyword, so valid values are whatever gnuplot supports. See below for a list of supported curve styles.


If true, requests that this curve be plotted on the y2 axis instead of the main y axis


Specifies how many values represent each data point. For 2D plots this defaults to 2; for 3D plots this defaults to 3.



Most of these come directly from Gnuplot commands. See the Gnuplot docs for details.

2D plotting

If we're plotting a piddle $y of y-values to be plotted sequentially (implicit domain), all you need is


If we also have a corresponding $x domain, we can plot $y vs. $x with

  plot($x, $y);

Simple style control

To change line thickness:

  plot(with => 'lines linewidth 4', $x, $y);

To change point size and point type:

  plot(with => 'points pointtype 4 pointsize 8', $x, $y);


To plot errorbars that show $y +- 1, plotted with an implicit domain

  plot(with => 'yerrorbars', tuplesize => 3,
       $y, $y->ones);

Same with an explicit $x domain:

  plot(with => 'yerrorbars', tuplesize => 3,
       $x, $y, $y->ones);

Symmetric errorbars on both x and y. $x +- 1, $y +- 2:

  plot(with => 'xyerrorbars', tuplesize => 4,
       $x, $y, $x->ones, 2*$y->ones);

To plot asymmetric errorbars that show the range $y-1 to $y+2 (note that here you must specify the actual errorbar-end positions, NOT just their deviations from the center; this is how Gnuplot does it)

  plot(with => 'yerrorbars', tuplesize => 4,
       $y, $y - $y->ones, $y + 2*$y->ones);

More multi-value styles

In Gnuplot 4.4.0, these generally only work in ASCII mode. This is a bug in Gnuplot that will hopefully get resolved.

Plotting with variable-size circles (size given in plot units, requires Gnuplot >= 4.4)

  plot(with => 'circles', tuplesize => 3,
       $x, $y, $radii);

Plotting with an variably-sized arbitrary point type (size given in multiples of the "default" point size)

  plot(with => 'points pointtype 7 pointsize variable', tuplesize => 3,
       $x, $y, $sizes);

Color-coded points

  plot(with => 'points palette', tuplesize => 3,
       $x, $y, $colors);

Variable-size AND color-coded circles. A Gnuplot (4.4.0) bug make it necessary to specify the color range here

  plot(cbmin => $mincolor, cbmax => $maxcolor,
       with => 'circles palette', tuplesize => 4,
       $x, $y, $radii, $colors);

3D plotting

General style control works identically for 3D plots as in 2D plots.

To plot a set of 3d points, with a square aspect ratio (squareness requires Gnuplot >= 4.4):

  plot3d(square => 1, $x, $y, $z);

If $xy is a 2D piddle, we can plot it as a height map on an implicit domain


Complicated 3D plot with fancy styling:

  my $pi    = 3.14159;
  my $theta = zeros(200)->xlinvals(0, 6*$pi);
  my $z     = zeros(200)->xlinvals(0, 5);

  plot3d(title => 'double helix',

         { with => 'pointslines pointsize variable pointtype 7 palette', tuplesize => 5,
           legend => 'spiral 1' },
         { legend => 'spiral 2' },

         # 2 sets of x, 2 sets of y, single z
         PDL::cat( cos($theta), -cos($theta)),
         PDL::cat( sin($theta), -sin($theta)),

         # pointsize, color
         0.5 + abs(cos($theta)), sin(2*$theta) );

3D plots can be plotted as a heat map. As of Gnuplot 4.4.0, this doesn't work in binary.

  plot3d( extracmds => 'set view 0,0',
          with => 'image',
          $xy );


To send any plot to a file, instead of to the screen, one can simply do

  plot(hardcopy => 'output.pdf',
       $x, $y);

The hardcopy option is a shorthand for the terminal and output options. If more control is desired, the latter can be used. For example to generate a PDF of a particular size with a particular font size for the text, one can do

  plot(terminal => 'pdfcairo solid color font ",10" size 11in,8.5in',
       output   => 'output.pdf',
       $x, $y);

This command is equivalent to the hardcopy shorthand used previously, but the fonts and sizes can be changed.


gpwin - exported constructor (synonymous with new)

 use PDL::Graphics::Gnuplot;
 $w = gpwin( $options );
 $w->plot( @plot_args );

This is just a synonym for the "new" method. It is exported into the current package by default for convenience.

new - object constructor

    $w = new PDL::Graphics::Gnuplot;
    $w->plot( @plot_args );

    $w = new PDL::Graphics::Gnuplot( device, %device_options, {plot_options} );
    $w->plot( @plot_args );

Creates a PDL::Graphics::Gnuplot object to make a persistent plot.

  my $plot = PDL::Graphics::Gnuplot->new({title => 'Object-oriented plot'});
  $plot->plot( legend => 'curve', sequence(5) );

The plot options can be passed into the constructor as a trailing hash ref; the curve options and the data are passed into the method. One advantage of making plots this way is that there's a gnuplot process associated with each PDL::Graphics::Gnuplot instance, so as long as $plot exists, the plot will be interactive. Also, calling $plot->plot() multiple times reuses the plot window instead of creating a new one.

Gnuplot interprets plot options differently per device. PDL::Graphics::Gnuplot attempts to interpret some of the more common ones in a common way. In particular:


Most drivers support a "size" option to specify the size of the output plotting surface. The format is [$width, $height, $unit]; the trailing unit string is optional but recommended, since the default unit of length changes from device to device.

The unit string can be in, cm, mm, px, or pt. Pixels are taken to be 1 point in size (72 pixels per inch) and dimensions are computed accordingly.


This option actually sets the object's "output" option for most terminal devices; that changes the file to which the plot will be written. Some devices, notably X11 and Aqua, don't make proper use of "output"; for those devices, specifying "output" in the object constructor actually sets the appropriate terminal option (e.g. "window" in the X11 terminal). This is described as a "plot option" in the Gnuplot manual, but it is treated as a setup variable and parsed with the setup/terminal options here in the constructor.


This is a flag that indicates whether to enable Gnuplot's enhanced text processing (e.g. for superscripts and subscripts). Set it to a false value for plain text, to a true value for enhanced text. See the Gnuplot manual for a description of the syntax.

For a brief description of the plot options that any one device supports, you can run PDL::Graphics::Gnuplot::terminfo().

As with plot options, terminal options can be abbreviated to the shortest unique string -- so (e.g.) "size" can generally be abbreviated "si" and "monochrome" can be abbreviated "mono" or "mo".

options - set/get persistent plot options for a plot object

  $w = new PDL::Graphics::Gnuplot();
  $w->options( globalwith=>'lines' );
  print %{$w->options()};

The options method parses plot options into a gnuplot object on a cumulative basis, and returns the resultant options hash.

If called as a sub rather than a method, options() changes the global gnuplot object.

restart - restart the gnuplot backend for a plot object


Occasionally the gnuplot backend can get into an unknown state. reset kills the gnuplot backend and starts a new one, preserving options state in the object.

Called with no arguments, restart applies to the global plot object.

reset - clear all state from the gnuplot backend


Clears all plot option state from the underlying object. All plot options except "terminal" and "output" are cleared. This is similar to the "reset" command supported by gnuplot itself.

gplot - exported plot method (synonym for "PDL::Graphics::Gnuplot::plot")

plot - method to generate a plot

The main plotting routine in PDL::Graphics::Gnuplot.

By default, each gplot() call creates a new plot in a new window.

 gplot({temp_plot_options},                 # optional
      curve_options, data, data, ... ,      # curve_options are optional for the first plot
      curve_options, data, data, ... );

Most of the arguments are optional.

 use PDL::Graphics::Gnuplot qw(plot);
 my $x = sequence(101) - 50;

See main POD for PDL::Graphics::Gnuplot for details.

For debugging and curiosity purposes, the last plot command issued to gnuplot is maintained in a package global: $PDL::Graphics::Gnuplot::last_plotcmd.

plot3d, splot

Generate 3D plots. Synonyms for plot(trid => 1, ...)


Generates plots with lines, by default. Shorthand for plot(globalwith => 'lines', ...)


Generates plots with points, by default. Shorthand for plot(globalwith => 'points', ...)


Displays an image (either greyscale or RGB)


 $a = (xvals(101)/100) * 6 * 3.14159/180;
 $b = sin($a);

 $w->plot({title=>"lines"}, with=>"lines", $a,$b);
 $w->plot({title=>"image"}, with=>"image", $a->(*1) * $b );

The multiplot method enables multiplot mode in gnuplot, which permits multiple plots on a single pane. Plots can be lain out in a grid, or can be lain out freeform using the size and origin plot options for each of the individual plots.

It is not possible to change the terminal or output device when in multiplot mode; if you try to do that, by setting one of those plot options, PDL::Graphics::Gnuplot will throw an error.

The options hash will accept:

layout - define a regular grid of plots to multiplot

layout should be followed by a hash ref that contains at least number of columns ("NX") followed by number of rows ("NY). After that, you may include any of the "rowsfirst", "columnsfirst", "downwards", or "upwards" keywords to specify traversal order through the grid. Only the first letter is examined, so (e.g.) "down" or even "dog" works the same as "downwards".

title - define a title for the entire page

title should be followed by a single scalar containing the title string.

scale - make gridded plots larger or smaller than their allocated space

scale takes either a scalar or a list ref containing one or two values. If only one value is supplied, it is a general scale factor of each plot in the grid. If two values are supplied, the first is an X stretch factor for each plot in the grid, and the second is a Y stretch factor for each plot in the grid.

offset - offset each plot from its grid origin

offset takes a list ref containing two values, that control placement of each plot within the grid.

terminfo - print out information about gnuplot syntax

    use PDL::Graphics::Gnuplot qw/terminfo/
    terminfo 'aqua'

terminfo is a reference tool to describe the Gnuplot terminal types and the options they accept. It's mainly useful in interactive sessions.


Everything should work on all platforms that support Gnuplot and Perl. That said, ONLY Debian GNU/Linux has been tested to work. Please report successes or failures on other platforms to the author. A transcript of a failed run with {log => 1} would be most helpful.



Dima Kogan, <> and Craig DeForest, <>


Copyright 2011 Dima Kogan and Craig DeForest

This program is free software; you can redistribute it and/or modify it under the terms of either: the GNU General Public License as published by the Free Software Foundation; or the Perl Artistic License.

See for more information.


Hey! The above document had some coding errors, which are explained below:

Around line 400:

You forgot a '=back' before '=head2'

Around line 900:

'=item' outside of any '=over'

Something went wrong with that request. Please try again.