PDL::G...nuplot(3pm)

🌈 PDL::Graphics::Gnuplot (3pm) 🌈

okay bestie, gather round πŸ’– you're reading the manual page for PDL::Graphics::Gnuplot β€” that's Gnuplot-based plotting for PDL β€” from the User Contributed Perl Documentation section. yes it's 3pm, yes we're doing this, and yes it's gonna be cute. πŸŽ€


✨ SYNOPSIS ✨

here's the vibe, copy-paste and go:

 pdl> use PDL::Graphics::Gnuplot;

 pdl> $x = sequence(101) - 50;
 pdl> gplot($x**2);
 pdl> gplot($x**2,{xr=>[0,50]});

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

 pdl> $xy = zeroes(21,21)->ndcoords - pdl(10,10);
 pdl> $z = inner($xy, $xy);
 pdl> gplot({title  => 'Heat map',
             trid   => 1,
             view   => [0,0]
            },
            with => 'image', xvals($z),yvals($z),zeroes($z),$z*2
           );

 pdl> $w = gpwin();                             # constructor
 pdl> $pi    = 3.14159;
 pdl> $theta = zeroes(200)->xlinvals(0, 6*$pi);
 pdl> $z     = zeroes(200)->xlinvals(0, 5);
 pdl> $w->plot3d(cos($theta), sin($theta), $z);
 pdl> $w->terminfo();                           # get information

like. look at that. plotting in four lines. slay. πŸ’…


πŸ’œ DESCRIPTION πŸ’œ

So what is this module even? It lets your PDL data get plotted through Gnuplot as the backend β€” for 2D and 3D plotting and image display. πŸ’– Quick note, no cap: Gnuplot is not affiliated with the GNU project (people get that wrong constantly, don't be that person). It's a venerable, open-source program that produces both interactive and publication-quality plots on lots and lots of different output devices. It's available through most Linux repositories, on MacOS, and from its website: http://www.gnuplot.info.

Now the good news: you do not have to understand gnuplot syntax to make basic β€” or even genuinely complex β€” plots. πŸ”₯ Like, at all. The full syntax is there for advanced users who want the full flexibility of the Gnuplot backend, but it is not a prerequisite. periodt.

Want a very quick demo of the power of this module? There's a YouTube demo video: https://www.youtube.com/watch?v=hUXDQL3rZ_0. There are others too β€” one on visualisation of tesseract assembly: https://www.youtube.com/watch?v=ykQmNrSKqGQ, and one on rotation: https://www.youtube.com/watch?v=6tpsPYBrHy0. go watch them, they're giving main character energy. πŸ‘‘

Gnuplot recognizes both hard-copy and interactive plotting devices. On interactive devices (like X11) you can pan, scale, and rotate both 2-D and 3-D plots interactively β€” yes, with your little hands, live. πŸ¦‹ You can also enter graphical data through mouse clicks on the device window. And heads up: on some hardcopy devices (e.g. "PDF") that support multipage output, it is necessary to close the device after plotting to ensure a valid file is written out. don't forget, bestie, or your file will simply not be a file. 😭

"PDL::Graphics::Gnuplot" exports two routines by default: a constructor, gpwin(), and a general purpose plot routine, gplot(). 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. versatile icon behavior honestly ✨

A call to gplot() looks like:

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

The data entries are columns to be plotted. They're normally an optional ordinate and a required abscissa, but some plot modes can use more columns than that. The collection of columns is called a "tuple". Each column must be a separate PDL or an ARRAY ref. And if all the columns are PDLs, you can add extra dimensions to make threaded collections of curves. πŸŒ€

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.

The gplot() sub (or the plot() method) collects two kinds of options hash:

  • plot options β€” these describe the overall structure of the plot being produced (e.g. axis specifications, window size, and title).
  • curve options β€” these 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 so 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 can specify what type of graphics output you want, but in most cases doing nothing will cause a plot to be rendered on your screen: with X windows on UNIX or Linux systems, with an XQuartz window on MacOS, or with a native window on Microsoft Windows. auto-magic. ✨

You select a plot style with the "with" curve option, and feed in columns of data (usually ordinate followed by abscissa). The collection of columns is called a "tuple". These plots have two columns in their tuples:

 $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. 🧡

All data are required to be supplied as either PDLs or array refs. If you use an array ref as a data column, then normal threading is disabled. For example:

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

See below for supported curve styles. πŸ’–

πŸŽ€ Modifying plots πŸŽ€

Gnuplot is built around a monolithic plot model β€” it is not possible to add new data directly to a plot without redrawing the entire plot. To support replotting, PDL::Graphics::Gnuplot stores the data you plot in the plot object, so that you can add new data with the "replot" command:

 $w=gpwin(x11);
 $x=xvals(101)/100;
 $y=$x;
 $w->plot($x,$y);
 $w->replot($x,$y*$y);

For speed, the data are not disconnected from their original variables β€” so this will plot X vs. sqrt(X):

 $x = xvals(101)/100;
 $y = xvals(101)/100;
 $w->plot($x,$y);
 $y->inplace->sqrt;
 $w->replot();
⚠️ bestie, read that again: the data are not disconnected from their original variables. mutate the variable, and you mutate the plot. it's giving "surprise!" πŸ’€

πŸ¦‹ Plotting to an image file or device πŸ¦‹

PDL:Graphics::Gnuplot can plot to most of the devices supported by gnuplot itself. You can specify the file type with the "output" method or the object constructor "gplot". Either one will allow you to name a type of file to produce, and a collection of options speciic to that type of output file.

(no i did not fix the typo, "speciic" stays, it's iconic 😌)

πŸ‘‘ Image plotting πŸ‘‘

Several of the plot styles accept image data. The tuple parameters work the same way as for basic plots, but each "column" is a 2-D PDL rather than a 1-D PDL. As a special case, the "with image" plot style accepts either a 2-D or a 3-D PDL. If you pass in 3-D PDL, the extra dimension can have size 1, 3, or 4. It is interpreted as running across (R,G,B,A) color planes. 🌈

⭐ 3-D plotting ⭐

You can plot in 3-D by setting the plot option "trid" to a true value. Three dimensional plots accept either 1-D or 2-D PDLs as data columns. If you feed in 2-D "columns", many of the common plot styles will generalize appropriately to 3-D. For example, to plot a 2-D surface as a line grid, you can use the "lines" style and feed in 2-D columns instead of 1-D columns. πŸ”₯

πŸ’« Enhanced text πŸ’«

Most gnuplot output devices include the option to markup "enhanced text". That means text is interpreted so that you can change its font and size, and insert superscripts and subscripts into labels. Codes are:

  • {} β€” Text grouping β€” enclose text in braces to group characters, as in LaTeX.
  • ^ β€” Superscript the next character or group (shrinks it slightly too where that is supported).
  • _ β€” Subscript the next character or group (shrinks it slightly too where that is supported).
  • @ β€” Phantom box (occupies no width; controls height for super- and subscripting)
  • & β€” Controllable-width space, e.g. &{template-string}
  • ~ β€” overstrike β€” e.g. ~a{0.8-} overprints '-' on 'a', raised by 0.8xfontsize.
  • {/[fontname][=fontsize | *fontscale] text} β€” Change font to (optional) fontname, and optional absolute font size or relative font scale ("fontsize" and "fontscale" are numbers). The space after the size parameter is not rendered.
  • \ β€” Backslash escapes control characters to render them as themselves.

🧚 Unicode text 🧚

Separately to "enhanced" text above, if you wish to include text that is not ASCII, then you will need to pass data that has been UTF-8 encoded. Sample code to achieve this:

   use utf8;
   use Encode;
   use PDL;
   use PDL::Graphics::Gnuplot;
   use PDL::Constants qw(PI);

   sub plot_sin {
     my ($w, $coeff) = @_;
     my $xrange = [ -2*PI, 2*PI ];
     my $x = zeroes(1e3)->xlinvals(@$xrange); my $y = sin($coeff * 2 * PI * $x);
     my $title = "y = sin( $coeff * 2Ο€ * x )";
     # to get around sending text through syswrite()
     my $title_octets = encode('UTF-8', $title);
     $w->plot(with=>'lines', $x, $y, {
       xrange => $xrange,
       title => $title_octets, # can not pass $title as-is
     });
   }

yes, you read the comment right: you can not pass $title as-is. encode it. 🫢

🌸 Color specification 🌸

There are several contexts where you can specify color of plot elements. In those places, you can specify colors exactly as in the Gnuplot manual, or more tersely. In general, a color spec can be any one of the following:

  • an integer β€” This specifies a recognizable unique color in the same order as used by the plotting engine.
  • the name of a color β€” (e.g. "blue"). Supported color names are listed in the variable @Alien::Gnuplot::colors.
  • an RGB value string β€” Strings have the form "#RRGGBB", where the "#" is literal and the RR, GG, and BB are hexadecimal bytes.
  • the word "palette" β€” "palette" indicates that color is to be drawn from the scaled colorbar palette (which you can set with the "clut" plot option), by lookup using an additional column in the associated data tuple.
  • the word "variable" β€” "variable" indicates that color is to be drawn from the integer plotting colors used by the plotting engine, indexed by an additional column in the associated data tuple.
  • the phrase "rgb variable" β€” "rgb variable" indicates that color is to be directly specified by a 24 bit integer specifying 8-bit values for (from most significant byte to least significant byte) R, G, and B in the output color. The integer is drawn from an additional column in the associated data tuple.

πŸŽ€ Plot styles supported πŸŽ€

Gnuplot itself supports a wide range of plot styles, and all are supported by PDL::Graphics::Gnuplot. 😀 Most of the basic plot styles collect tuples of 1-D columns in 2-D mode (for ordinary plots), or either 1-D or 2-D "columns" in 3-D mode (for grid surface plots and such). Image modes always collect tuples made of 2-D "columns".


to be continued, bestie πŸ’–

You can hand in those 1-D columns as either PDLs or ARRAY refs. This matters a LOT for plot types like labels that want a whole collection of strings instead of numbers, bestie. πŸ’…

Every plot style can be tweaked to rock particular colors or line style options, and those tweaks get passed in as curve options (more on those below πŸ‘‡). So like, if you wanna plot a blue line you go with=>'lines',lc=>'blue'. And if you wanna match the autogenerated style of some specific line, you use the ls curve option.

The GNuplot plot styles supported are:

  • boxerrorbars β€” combo of boxes and yerrorbars, below (2D) πŸŽ€
  • boxes β€” simple boxes around regions on the plot (2D)
  • boxxyerrorbars β€” render X and Y error bars as boxes (2D)
  • candlesticks β€” Y error bars with inner and outer limits (2D)
  • circles β€” circles with variable radius at each point: X/Y/radius (2D)
  • dots β€” tiny points (dots) at each point, e.g. for scatterplots (2D/3D)
  • ellipses β€” ellipses. Accepts X/Y/major/minor/angle (2D)
  • filledcurves β€” closed polygons or axis-to-line filled shapes (2D)
  • financebars β€” financial style plot. Accepts date/open/low/high/close (2D) πŸ“ˆ
  • fsteps β€” square bin plot; delta-Y, then delta-X (see steps, histeps) (2D)
  • histeps β€” square bin plot; plateaus centered on X coords (see fsteps, steps) (2D)
  • histogram β€” binned histogram of dataset (not direct plot; see newhistogram) (2D)
  • fits β€” (PDL-specific) renders FITS image files in scientific coordinates πŸ”­
  • image β€” Takes (i), (x,y,i), or (x,y,z,i). See rgbimage, rgbalpha, fits. (2D/3D)
  • impulses β€” vertical line from axis to the plotted point (2D/3D)
  • labels β€” Text labels at specified locations all over the plot (2D/3D) 🏷️
  • lines β€” regular line plot (2D/3D)
  • linespoints β€” line plot with symbols at plotted points (2D/3D)
  • newhistogram β€” multiple-histogram-friendly histogram style (see histogram) (2D)
  • points β€” symbols at plotted points (2D/3D)
  • rgbalpha β€” R/G/B color image with variable transparency (2D/3D) 🌈
  • rgbimage β€” R/G/B color image (2D/3D)
  • steps β€” square bin plot; delta-X, then delta-Y (see fsteps, histeps) (2D)
  • vectors β€” Small arrows: (x,y,[z]) -> (x+dx,y+dy,[z+dz]) (2D/3D)
  • xerrorbars β€” points with X error bars (T form) (2D)
  • xyerrorbars β€” points with both X and Y error bars (T form) (2D)
  • yerrorbars β€” points with Y error bars (T form) (2D)
  • xerrorlines β€” line plot with X errorbars at each point. (2D)
  • xyerrorlines β€” line plot with XY errorbars at each point. (2D)
  • yerrorlines β€” line plot with Y error limits at each point. (2D)
  • pm3d β€” three-dimensional variable-position surface plot ✨

Options arguments 🫢

Ok so plot options are the parameters that affect the whole entire plot β€” think the title of the plot, the axis labels, the extents, the whole 2d/3d selection situation, all of it. Every single one of them is described below in Plot Options.

You can set plot options in the plot object, OR pass them straight to the plotting methods. And you can pass them in as a leading interpolated hash, a leading hash ref, OR a trailing hash ref in the argument list to any of the main plotting routines (gplot, plot, image, etc.).

Curve options, on the other hand, are the parameters that affect just one single curve. Each call to plot() can hold soooo many curves, and the options for one particular curve go right before the data for that curve in the argument list. The actual type of curve (the with option) is persistent, but literally all the other curve options and modifiers are not. Example time:

 gplot( with => 'points',  $x, $a,
        {axes=> x1y2},     $x, $b,
        with => 'lines',   $x, $c );

So this plots 3 whole curves: $a vs. $x plotted with points on the main y-axis (that's the default btw), $b vs. $x plotted with points on the secondary y axis, and $c vs. $x plotted with lines on the main y-axis (the default again). And note that the curve options can come in as either an inline hash or a hash ref. Flexible, iconic. πŸ’–

All the curve options are described below in Curve Options.

And listen β€” if you wanna plot multiple curves of the same type without setting any curve options explicitly, you must include an empty hash ref between the tuples for the subsequent lines, like:

 gplot( $x, $a, {}, $x, $b, {}, $x, $c );

Data arguments 🌸

Following the curve options in the plot() argument list comes the actual data being plotted. Each output data point is a tuple whose size varies depending on what's being plotted. So like, 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 has to be passed separately. For ordinary 2-D plots, the 0 dim of the tuple elements runs across plotted point.

PDL threading is active, so you can plot multiple curves with similar curve options on a normal 2-D plot just by stacking data inside the passed-in PDLs. (The one exception: threading is disabled if one or more of the data elements is a list ref.)

PDLs vs array refs

The usual way to pass in data is as a PDL β€” one PDL per column of data in the tuple. But strings, in particular, cannot easily be hammered into PDLs 😭. Therefore any column in each tuple can be an array ref holding values (numeric or string). The column gets interpreted using the usual polymorphous cast-behind-your-back behavior of Perl. And for the sake of sanity: if even one array ref is present in a tuple, then threading is disabled in that tuple β€” everything has to have a nice 1-D shape.

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 PDL is given here, but the plot type (lines by default) requires 2 elements per tuple. So we are exactly 1 ndarray short; sequence(5) is used as the missing domain PDL. Which makes it equivalent to plot(sequence(5), pdl(1,5,3,4,4) ). Slay. ✨

If plotting in 3d or displaying an image, an implicit domain will be used if we are exactly 2 ndarrays 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);
 gplot({'3d' => 1},
        with => 'points', inner($xy, $xy));
 gplot( with => 'image',  sin(rvals(51,51)) );

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

PDL::Graphics::Gnuplot requires explicit separators between tuples for different plots, so it's always clear from the arguments you pass in just how many columns you are supplying. For example, plot($a,$b) will plot $b vs. $a. If you actually want to plot an overlay of both $a and $b against array index, you want plot($a,{},$b) instead. The {} is a hash ref containing a collection of all the curve options that you're changing between the two curves β€” in this case, zero of them. πŸ’€


Images πŸ¦‹

PDL::Graphics::Gnuplot supports four styles of image plot, 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 (3xWxH) or (WxHx3) PDL it is treated as an RGB image and displayed with the rgbimage style (below), provided there are at least 5 pixels in each of the other two dimensions (just to be sure πŸ‘€). For quick image display there's also a whole image method:

 use PDL::Graphics::Gnuplot qw/image gplot/;
 $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
 gplot( 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:

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

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

 gplot( 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. 🫠

PDL::Graphics::Gnuplot provides a fits plot style that interprets World Coordinate System (WCS) information supplied in the header of the scientific image format FITS. The image is displayed in rectified scientific coordinates, rather than in pixel coordinates. You can plot FITS images in scientific coordinates with

 gplot( with=>'fits', $fitsdata );

The fits plot style accepts a curve option resample (which may be abbreviated), that allows you to downsample and/or rectify the image before it is passed to the Gnuplot back-end. This is useful either to cut down on the burden of transferring large blocks of image data or to rectify images with nonlinear WCS transformations in their headers. (gnuplot itself has a bug that prevents direct rendering of images in nonlinear coordinates. πŸ™ˆ)

 gplot( with=>'fits', res=>1, $fitsdata );
 gplot( with=>'fits', res=>[200], $fitsdata );
 gplot( with=>'fits', res=>[100,400],$fitsdata );

to specify that the output are to be resampled onto a square 1024x1024 grid, a 200x200 grid, or a 100x400 grid, respectively. The resample sizes must be positive integers. A true non-ref value will be treated as 1024x1024.


Interactivity πŸŽ€

Several of the graphical backends of Gnuplot are interactive, letting you pan, zoom, rotate and measure the data interactively right there in the plot window. Peep the Gnuplot documentation for the details on how to do all that.

Some terminals (like wxt) are persistently interactive. Other terminals (like 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 ⏳). And still others (the hardcopy devices) aren't interactive at all. πŸ’…

Some interactive devices (notably wxt and x11) also support mouse input: you can write PDL scripts that accept and manipulate graphical input from the plotted window. πŸ–±οΈβœ¨ it's giving literally hands-on plotting bestie.

🌈 PLOT OPTIONS 🌈

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. no cap. 🫢

There are many, many plot options. For convenience, we've grouped them by general category below. Each group has a heading "POs for <foo>", describing the category. You can skip below them all if you want to read about curve options or other aspects of PDL::Graphics::Gnuplot. πŸ‘‘


πŸ–¨οΈ POs for Output: terminal, termoption, output, device, hardcopy

You can send plots to a variety of different devices; Gnuplot calls devices "terminals". With the object-oriented interface, you must set the output device with the constructor PDL::Graphics::Gnuplot::new (or the exported constructor gpwin) or the output method. If you use the simple non-object interface, you can set the output with the terminal, termoption, and output plot options.

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, attempts to parse out a file suffix and infer a device type. hardcopy also uses a common set of terminal options needed to fill an entire letter page with a plot. πŸ“„βœ¨

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 available terminals or, if you pass in a terminal name, options accepted by that terminal. it's giving encyclopedic queen πŸ‘‘


🏷️ POs for Titles

The options described here are

  • title
  • xlabel
  • x2label
  • ylabel
  • y2label
  • zlabel
  • cblabel
  • 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 doesn't set a label at all, rather specifies the printf format used by contour labels in contour plots. πŸ’€ classic trap bestie)

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 an array 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 comma-delimited string 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

The options described here are

  • grid
  • xzeroaxis
  • x2zeroaxis
  • yzeroaxis
  • y2zeroaxis
  • zzeroaxis
  • border

Normally, tick marks and their 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. periodt.

  • <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. 🧊 iconic honestly

  • ( 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. πŸ’…

The grid option indicates whether gridlines should be drawn on each axis. It takes an array ref of arguments, each of which is 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. ✨

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

The zeroaxis keyword indicates whether to actually draw each axis line at the corresponding zero along its indicated dimension. For example, 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 an array ref containing linewidth, linestyle, and linetype (with appropriate parameters for each), e.g. xzeroaxis=>[linewidth=>2]. 🌸


πŸ“ POs for axis range and mode

The options described here are

  • xrange
  • x2range
  • yrange
  • y2range
  • zrange
  • rrange
  • cbrange
  • trange
  • urange
  • vrange
  • autoscale
  • logscale

Gnuplot accepts explicit ranges as plot options for all axes. Each option accepts an array 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 hash ref, each element of which specifies how a single axis should be autoscaled. Each keyword contains an axis name followed by one of fix, min, max, fixmin, or fixmax. You can set all the axes at once by setting the keyword name to ' '. Examples:

 autoscale=>{x=>'max',y=>'fix'};

There is an older array ref syntax which is deprecated but still accepted. ⚠️

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 an array 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']. πŸ“ˆ slay


🎯 POs for Axis tick marks

The options described here are

  • xtics
  • x2tics
  • ytics
  • y2tics
  • ztics
  • cbtics
  • mxtics
  • mx2tics
  • mytics
  • my2tics
  • mztics
  • mcbtics

Axis 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 "POs for time data values" below). ⏰✨

By default, gnuplot will just auto-place your major and minor ticks, no thoughts head empty, and honestly? slay πŸ’…. But if you wanna be the main character, you can turn ticks off on an axis by setting the matching {foo}tics option to a defined, false scalar value (like xtics=>0). Want major tics landing at a regular specified interval? Set the matching tics option to a nonzero scalar value (so xtics=>2 = a tic every 2 units on the X axis, iconic). And if you just want the default tick positioning back, hand it an empty hash or array ref (like xtics=>{}), or a string containing only whitespace (like xtics=>' '). ✨

Ok but here's the glow-up: 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 β€” iykyk πŸ“)

Every tics option can accept a hash ref stuffed with options to pass to Gnuplot. You can also pass in a snippet of gnuplot command, as either a string or an array ref β€” but those techniques are deprecated and may disappear in a future version of PDL:Graphics::Gnuplot, so maybe don't get attached 🫠.

The keywords are case-insensitive and may be abbreviated, just like with other option types. Behold:

  • axis β€” set to 1 to place tics on the axis (this is the default)
  • border β€” set to 1 to place tics on the border (not the default!)
  • mirror β€” set to 1 to place mirrored tics on the opposite axis/border (the default, unless an alternate axis interferes β€” e.g. y2)
  • in β€” set to 1 to draw tics inward from the axis/border
  • out β€” set to 1 to draw tics outward from the axis/border
  • scale β€” multiplier on tic length compared to the default
    • if you pass in undef, tics get the default length
    • if you pass in a scalar, major tics get scaled
    • and you can pass in an array ref to scale minor tics too πŸ‘‘
  • rotate β€” turn label text by the given angle (in degrees) on the drawing plane
  • offset β€” offset label text from default position (units: characters; requires an array ref containing x,y)
  • locations β€” sets tic locations. Gets an array ref: [incr], [start, incr], or [start, incr, stop].
  • labels β€” sets tic locations explicitly, with text labels for each. If you specify both locations and labels, you get both sets of tics on the same axis. The labels should be a nested array ref that is a collection of duals or triplets. Each dual or triplet should contain [label, position, minorflag], as in labels=>[["one",1,0],["three-halves",1.5,1],["two",2,0]].
  • format β€” printf-style format string for tic labels. There are some extensions to the gnuplot format tags β€” see the gnuplot manual. Gnuplot 4.8 and higher have %h, which works like %g but uses extended text formatting if it is available.
  • font β€” set font name and size (system font name)
  • rangelimited β€” set to 1 to limit tics to the range of values actually present in the plot
  • textcolor β€” set the color of the tick labels (see "Color specification")

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

xtics => {axis=>1,mirror=>1,in=>1,rotate=>45,font=>'Arial,9'}

or

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

🌈 POs for time data values 🌈

The options described here are

xmtics
x2mtics
ymtics
y2mtics
zmtics
cbmtics
xdtics
x2dtics
ydtics
y2dtics
zdtics
cbdtics
xdata
x2data
ydata
y2data
zdata
cbdata

Gnuplot contains support for plotting absolute time and date on any of its axes, with conventional formatting. There are three main methods, which are mutually exclusive (i.e. you should not attempt to use two at once on the same axis β€” pick one bestie, no double-dipping πŸ™ˆ).

πŸ•°οΈ 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 time (seconds since the UNIX epoch, neglecting leap seconds). No provision is made for UT-TAI conversion. 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=>"%Y-%b-%dT%H:%M:%S"} will plot UNIX times as ISO timestamps in the ordinate. ⭐

Due to limitations within gnuplot, the time resolution in this mode is limited to 1 second β€” if you want fractional seconds, you must use numerically formatted times (and/or create your own tick labels using the labels suboption to the ?tics option). No cap, that's just the limit bestie 😭

πŸ’– Timestamp format specifiers πŸ’–

Time format specifiers use the following printf-like codes:

  • Year A.D.: %Y is 4-digit year; %y is 2-digit year (1969-2068)
  • Month of year: %m: 01-12; %b or %h: abrev. name; %B: full name
  • Week of year: %W (week starting Monday); %U (week starting Sunday)
  • Day of year: %j (1-366; boundary is midnight)
  • Day of month: %d (01-31)
  • Day of week: %w (0-6, Sunday=0), %a (abrev. name), %A (full name)
  • Hour of day: %k (0-23); %H (00-23); %l (1-12); %I (01-12)
  • Am/pm: %p ("am" or "pm")
  • Minute of hour: %M (00-60)
  • Second of minute: %S (0-60)
  • Total seconds since start of 2000 A.D.: %s
  • Timestamps: %T (same as "%H:%M:%S"); %R (same as "%H:%M"); %r (same as "%I:%M:%S %p")
  • Datestamps: %D (same as "%m/%d/%y"); %F (same as "%Y-%m-%d")
  • ISO timestamps: use "%DT%T".

πŸ—“οΈ 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. As far as output format goes, this is exactly equivalent to using the %w option with full formatting β€” but you can treat the numeric range in terms of weeks rather than seconds. 🌸

πŸŽ€ 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. This is exactly equivalent to using the %d option with full formatting β€” but you can treat the numeric range in terms of months rather than seconds. 🎁


πŸ“ POs for location/size πŸ“

The options described here are

tmargin
bmargin
lmargin
rmargin
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. Custom layouts? We love to see it πŸ’…

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. So precise, so iconic ✨

The offsets option allows you to put an empty boundary around the data, inside the plot borders, in an autoscaled graph. The offsets only affect the x1 and y1 axes, and only in 2D plot commands. offsets accepts an array 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. Tall queen energy πŸ‘‘

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, pseudocolor, pc, perceptual, pcp 🎨

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 an array 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'. clut is maintained but is superseded by pc and pcp (below), which give access to a better variety of color tables, and have better support for scientific images. Science slay fr fr πŸ”₯

"pseudocolor" (synonym "pc") πŸ’… β€” okay so this one hands you the color tables that live inside the PDL::Transform::Color package, if that package is even installed on your little machine. It'll accept either a color table name, or an array ref which is basically a lil bundle of arguments that get yeeted straight into the PDL::Transform::Color::t_pc transform definition method. Send it the empty string, or undef, and it'll spit out a list of allowable color table names for you ✨. Also, tons of these color tables are "photometric", which means they render photometric data correctly with no gamma correction needed. Slay.

"perceptual" (synonym "pcp") β€” same hookup to PDL::Transform::Color as "pseudocolor", but it uses "equal-perceptual-difference" scaling instead. Translation: the module gamma-corrects your input values so that uniform shifts in numeric value give you approximately uniform perceptual shifts. It's giving "my eyes perceive this as a smooth gradient" energy πŸ¦‹.

If you use "pseudocolor" or "perceptual", and if PDL::Transform::Color can actually be loaded, then that external module is what defines a custom Gnuplot palette by linear interpolation across 256 values ⭐. That palette is then used to translate your monochrome data into a color image. The Gnuplot output is assumed to be sRGB. This is probably fine for most output devices, ngl.


✨ 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 what switches between the Gnuplot plot and splot command, but bestie, it's tracked with persistent state just like every other option, so it doesn't just vanish after one use.

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 just... stop, and omit the rest πŸ™ˆ. 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. Main character energy.

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 they're explained in the gnuplot manual. (Not me gatekeeping... anyway.)

"hidden3d" accepts a list of parameters to control how hidden surfaces are plotted (or, like, not plotted) in 3D. It accepts a boolean argument saying whether to hide "hidden" surfaces and lines; or an array ref containing parameters that control how hidden surfaces and lines are handled. For the 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. So:

  • 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. So 0 places it at the bottom of the plotted Z axis, and -1 places it at the top of the plotted Z axis. iykyk πŸ’…

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


✨ POs for Contour plots β€” contour, cntrparam ✨

Contour plots are only implemented in 3D, bestie. 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. Yeah, it's convoluted, for sure 😭 β€” future versions of this module may have a cleaner way to do it. We're just vibing with what we have.

"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 an array ref with a collection of Gnuplot parameters that are issued one per line; refer to the Gnuplot manual for how to actually 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 (or you can add it later with the "replot" method πŸ”). These options give you access to a collection of (separately) numbered descriptions that get accumulated into the plot object. To add a markup object to the next plot, supply the appropriate options as an array ref or as a single string. To specify all the 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 array 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> β€” the text you want to place on the plot. You may supply double-quotes inside the string, but it's 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 an (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 the details.
  • ( left | center | right ) β€” text placement relative 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
label3=>["foo",at=>"3,4",font=>'"Helvetica,18"']
  • 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> β€” offset 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 arrow2=>["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 particular predeclared numerical style. If you give this parameter, you should 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 πŸ’–

"object"s 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> β€” the 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, or center=>$pos,, followed by size=>$radius and (optionally) arc=>"[$begin:$end]".
    • You can specify a polygon with from=>$pos1,to=>$pos2,to=>$pos3,...to=>$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 ✨

"bars" sets the width and behavior of the tick marks at the ends of error bars πŸ“Š. It takes a list containing at most two elements, both of which are optional:

  • A width specifier, which should be a numeric size multiplier times the usual width (which is about one character width in the default font size), or the word "fullwidth" to make the ticks the same width as their associated boxes in boxplots and histograms.
  • The word "front" or "back" to indicate drawing order in plots that might contain filled rectangles (e.g. boxes, candlesticks, or histograms) πŸ’…

If you hand me the undefined value, you get zero ticks on those errorbars β€” nothing. Hand me an empty array ref instead and you get the default ticks. Little choices, big energy. ✨

boxwidth = how wide the drawn boxes are in boxplots, candlesticks and histograms. It takes a list with at most two things in it:

  • a numeric width
  • one of the words absolute or relative.

Unless you say relative, that numeric width is the width of boxes in X-axis scientific units (and heads up β€” on log scales this gets measured at x=1 and that same width gets used all across the plot plane, so no sneaky rescaling). If you do include relative, then the numeric width isn't a size at all β€” it's a multiplier on the default width. πŸ’…

isosamples sets how dense the isolines are when you're plotting functions as surfaces. You give it one or two numbers. First one = number of iso-u lines, second = number of iso-v lines. Give it only one and it just uses it for both, twin moment. 🫢 From the gnuplot manual, quote unquote: "An isoline is a curve parameterized by one of the surface parameters while the other surface parameter is fixed. Isolines provide a simple means to display a surface. By fixing the u parameter of surface s(u,v), the iso-u lines of the form c(v) = s(u0,v) are produced, and by fixing the v parameter, the iso-v lines of the form c(u)=s(u,v0) are produced". So now you know, iykyk. 🌸

pointsize takes a single number and scales how big the points are in your plots. Tiny dots, giant dots, you decide bestie. πŸ”₯

style is where the customization goes feral. It gives you a whole lot of control over individual plot styles. Fair warning tho β€” it is not (yet) fully parsed by PDL::Graphics::Gnuplot, so for the full tea please refer to the Gnuplot manual (it's pp. 145ff in the Gnuplot 4.6.1 manual, page numbers and everything, iconic). style takes a hash ref whose keys are plot styles (the same kind of thing you'd feed to the with curve option) and whose values are array refs holding keywords and other parameters that modify how each plot style should show up. πŸŽ€

🌍 POs for locale/internationalization - locale, decimalsign 🌍

locale controls date stamp creation. See the gnuplot manual for the deets.

decimalsign takes a character to use instead of a "." for the decimalsign β€” like when European countries do decimalsign=>','. Comma supremacy, honestly. ⭐

globalwith is the default plot style, used whenever there's no valid with curve option present for a given curve.

Set timestamp to a nonzero value and you get a time stamp placed on the side of the plot β€” perfect for keeping track of drafts like the little archivist you are. πŸ¦‹

zero sets the approximation threshold for zero values inside gnuplot. Default is 1e-8. Not zero, basically zero. πŸ’€

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

πŸ”§ POs for advanced Gnuplot tweaks: topcmds, extracmds, bottomcmds, binary, dump, tee πŸ”§

So here's the lore: plotting happens by sending a pile of commands to an underlying gnuplot process. In general, the plot options make set commands get sent, configuring gnuplot to make your plot. Then a plot or splot command comes along, followed by whatever cleanup is needed to keep gnuplot in a known state. πŸ’–

Provisions exist for sending commands directly to Gnuplot as part of a plot. You can drop commands at the top of the configuration but just under the initial set terminal and set output commands (that's the topcmds option), at the bottom of the configuration and just before the plot command (that's extracmds), or after the plot command (that's bottomcmds). Each of these plot options takes an array ref, and every element of it should be one command line for gnuplot. One command per element, no multitasking. 😌

Most plotting is done with binary data transfer to Gnuplot. However β€” because of some bugs in Gnuplot's binary handling, certain types of plot data get sent in ASCII instead. Specifically, time series and label data require transmission in ASCII (as of Gnuplot 4.4). If you want to force ASCII transmission of everything except image data, explicitly set the binary=>0 option. 🌈

dump is for debugging. If it's true, it writes out the gnuplot commands to STDOUT instead of writing to a gnuplot process. Super useful for seeing what commands would be sent to gnuplot. This is a dry run β€” nobody actually plots, it's just vibes and text. πŸ‘‘

Heads up bestie: if the binary option is given (see below), then this dump will contain binary data. If you want that binary data suppressed from the dump, set dump => 'nobinary'. 🫢

tee is also for debugging. If it's true, it writes the gnuplot commands to STDERR in addition to writing to a gnuplot process. This is NOT a dry run: the data really does go to gnuplot and to the log. Great for debugging I/O issues. Note that if the binary option is given (see below), then this log will contain binary data. If that binary data should be suppressed from the log, set tee => 'nobinary'. πŸ’…

πŸ’… CURVE OPTIONS πŸ’…

okay so CURVE OPTIONS</p> are the ✨glow-up✨ details for individual curves inside your plot. like, the plot options are the whole party, and curve options are what each little line is wearing. they live in a hash, and the keys are all of these πŸ‘‡


  • legend β€” this is the label that shows up for this curve in the legend. give your curve a name bestie, she deserves one πŸŽ€
  • axes β€” lets you say which X and/or Y axes to plot on. gnuplot has a main and an alternate X and Y axis, so you hand it a packed string with the x and y axes in it. so like, "x1y1" plots on the main axes, and "x1y2" plots using an alternate Y axis (which normally gets gridded over on the right side of the plot). ✨
  • with β€” the plot style for this curve. the value just gets passed straight to gnuplot through its with keyword, so literally whatever gnuplot supports is fair game. peep above ("Plot styles supported") for the curated list of supported curve styles.

the curve options below this one modify the plot style even further. heads up tho: not all of them make sense for all plot styles β€” like, specifying a fill style for with=>lines? that's giving nothing, it does nothing.

for historical reasons 😭 you can supply the with-modifier curve options as one single string inside the with curve option. that usage is deprecated and is going to vanish in a future version of PDL::Graphics::Gnuplot. so don't get attached.

  • linetype (abbrev lt) β€” a numeric selector from the default collection of line styles. it automagically picks the dash style, color, and width from your current output terminal's default set of linetypes. iconic behavior honestly.
  • dashtype (abbrev dt) β€” this can be either a numeric type selector (0 = no dashes) or an ARRAY ref holding a list of up to 5 pairs of (dash length, space length). note: the dashtype curve option is only supported on gnuplot 5.0 and up.

if you don't set a dashtype curve option, the default behavior matches the older gnuplots: lots of terminals support a dashed terminal/output option, and if you've set that (in the constructor or via the output method) then lines get uniquely dashed by default. want one specific curve solid? set dt=>0 as a curve option just for it. want all curves solid? use the constructor or the output method to set the terminal option dashed=>0.

if your gnuplot is older than v5.0, the dashtype curve option is ignored, and it emits a warning about it. rude but true.

  • linestyle (abbrev ls) β€” works exactly like linetype up above, except you can also modify individual line styles by setting the style line <num> plot option. super handy for a custom style you might reuse across several curves, whether that's in one plot or across several plots. 🫢
  • linewidth (abbrev lw) β€” a numeric multiplier on the usual default line width for your current terminal.
  • linecolor (abbrev lc) β€” the color specifier for the line's color. see "Color specification". you can feed in a standard color name (they're all listed in the package-global variable @PDL::Graphics::Gnuplot::colornames), a small integer indexing the standard linetype colors, the word variable to say the line color is a standard linetype color drawn from an extra column of data, a string of the form #RRGGBB (where the # is literal and the RR, GG, BB are hexadecimal bytes), the words rgbcolor variable to specify an extra data column holding 24-bit packed integers with RGB color values, [palette=>'frac',<val>] for a single fractional position (scaled 0-1) in the current palette, or [palette=>'cb',<val>] for a single value in the scaled cbrange.

there is no linecolor=>[palette=>variable] because of Gnuplot's non-orthogonal syntax. to draw line color from the palette via an extra data column, go look at the separate palette curve option (down below πŸ‘‡).

  • textcolor (abbrev tc) β€” for plot styles that specify text, like labels, this sets the color of the text. same format as linecolor above. πŸ’œ
  • pointtype (abbrev pt) β€” picks a point glyph shape out of the built-in list for your terminal, for plots that render points as little glyphs (like points and linespoints).
  • pointsize (abbrev ps) β€” picks a fractional size for point glyphs, relative to your terminal's default size, for plots that render points as little glyphs.
  • fillcolor (abbrev fc) β€” fills an area plot like filledcurves with a color. same format as linecolor. this fills the whole plot with the same color. to fill above a threshold or below a threshold, you need the above and below options.

here's an example plotting data in a single function call, no cap:

plot({ with => 'filledcurves', fillcolor => 'green', above => 'y=0' },
    x, y,
    { with => 'filledcurves', fillcolor => 'red', below => 'y=0' },
    x, y);
  • below β€” used for filledcurves to set a fillcolor below a threshold. you can set the value like y=0 if you want to color below the Y-axis value of 0.
  • above β€” used for filledcurves to set a fillcolor above a threshold. you can set the value like y=0 if you want to color above the Y-axis value of 0.
  • fillstyle (abbrev fs) β€” how filled regions get colored, in plots with fillable areas (like boxes). unlike linestyle above, fillstyle takes a full specification instead of an index into a set of predefined styles. you can feed in: 'empty' for no fill; 'transparent solid <density>' for a solid fill with optional <density> from 0.0 to 1.0 (default 1.0); 'transparent pattern <n>' for a pattern fill β€” plotting multiple datasets makes the pattern cycle through all the available pattern types, starting from pattern <n> (be aware that the default <n>=0 may be equivalent to 'empty'). the 'transparent' parts of those strings are optional, and only do anything on terminals that support transparency. and ngl, the quality of the visual output may depend on your terminal type and rendering software. πŸ¦‹

any of those fill style specification strings can have a border specification string appended. to specify a border, append 'border', and then optionally either 'lt=><type>' or 'lc=><colorspec>' onto the string. to specify no border, append 'noborder'.

  • nohidden3d β€” if you're making a 3D plot and used the plot option hidden3d to get hidden line removal, you can override that for one specific curve by setting nohidden3d to a true value. only the single curve with nohidden3d set gets its hidden points rendered. main character energy, honestly. πŸ‘‘
  • nocontours β€” if you're making a contour 3D plot, you can block contour rendering for one particular curve by setting nocontours to a true value.
  • nosurface β€” if you're making a surface 3D plot, you can block rendering of the surface for one particular curve by setting nosurface to a true value.
  • palette β€” setting palette => 1 makes the line color get drawn from an extra column in the data tuple. that column is always the very last column in the tuple whenever there's a conflict β€” so like, if you set both pointsize=>variable and palette=>1, then the palette column is last and the pointsize column is second-to-last. πŸ’…
  • tuplesize β€” how many values represent each data point. normally you don't need to set this, because individual with styles implicitly set a tuple size (and it auto-extends if you add extra modifiers like palette that need more data). this option just lets you override PDL::Graphics::Gnuplot's parsing when things get irregular.
  • cdims β€” the dimensions of each column in this curve's tuple. it must be 0, 1, or 2. normally you don't need to set this for most plots; the main use is saying that a 2-D data PDL should be read as a collection of 1-D columns instead of one single 2-D grid (which is the default in a 3-D plot). for example:
$w=gpwin();
$r2 = rvals(21,21)**2;
$w->plot3d( wi=>'lines', xvals($r2), yvals($r2), $r2 );

this makes a grid of values on a paraboloid. to instead plot a collection of lines using threaded syntax, try:

$w->plot3d( wi=>'lines', cd=>1, xvals($r2), yvals($r2), $r2 );

which plots 21 separate curves in a threaded manner. slay. ✨

  • resample β€” for with=>'fits'. see "Images". 🌈

🍳 RECIPES

Okay bestie, most of these are straight-up Gnuplot commands with a PDL glow-up ✨. If you wanna go deeper, the Gnuplot docs are right there.


🌈 2D plotting

If you're plotting an ndarray $y of y-values that just get plotted one after another (implicit domain), literally all you need is:

gplot($y);

And if you've also got a matching $x domain, you can plot $y vs. $x with:

gplot($x, $y);

πŸŽ€ Simple style control

Wanna change the line thickness? Say less:

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

Wanna change point size and point type? Periodt:

gplot(with => 'points',pointtype=>8, $x, $y);
gplot(with => 'points',pt=>8, $x, $y);

πŸ“‰ Errorbars

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

gplot(with => 'yerrorbars', $y, $y->ones);

Same thing but with an explicit $x domain:

gplot(with => 'yerrorbars', $x, $y, $y->ones);

Symmetric errorbars on both x and y β€” $x +- 1, $y +- 2:

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

And to plot asymmetric errorbars showing the range $y-1 to $y+2 β€” heads up bestie, here you must specify the actual errorbar-end positions, NOT just their deviations from the center; that's just how Gnuplot does it:

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

🌸 More multi-value styles

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

gplot(with => 'circles', $x, $y, $radii);

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

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

Color-coded points, slay:

gplot(with => 'points', palette=>1,
      $x, $y, $colors);

Variable-size AND color-coded circles πŸ’… β€” note that a Gnuplot (4.4.0) bug makes it necessary to specify the color range here:

gplot(cbmin => $mincolor, cbmax => $maxcolor,
      with => 'circles', palette=>1,
      $x, $y, $radii, $colors);

πŸš€ 3D plotting

General style control works identically for 3D plots as it does in 2D plots. Love that for us.

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

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

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

splot($xy);

Complicated 3D plot with fancy styling, main character energy fr:

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

splot(title => 'double helix',

      { with => 'linespoints',
        pointsize=>'variable',
        pointtype=>7,
        palette=>1,
        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)),
      $z,

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

3D plots can be plotted as a heat map too:

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

πŸ–¨οΈ Hardcopies

Wanna send any plot to a file instead of to the screen? Just do:

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

The hardcopy option is a shorthand for the terminal and output options, and the output device gets chosen from the file name suffix. Cute right?

If you want more (or literally any) control over the output options β€” page size, font, etc. β€” then you can specify the output device using the output method or the constructor itself, or the corresponding plot options in the non-object mode. For example, to generate a PDF of a particular size with a particular font size for the text, you can do:

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

This command is equivalent to the hardcopy shorthand we used before, except now the fonts and sizes can be changed. Glow-up complete ✨

Using the object oriented mode, you could instead say:

$w = gpwin();
$w->plot( $x, $y );
$w->output( pdfcairo, solid=>1, color=>1,font=>',10',size=>[11,8.5,'in'] );
$w->replot();
$w->close();
⚠️ Lowkey important: many hardcopy output terminals (like pdf and svg) will not dump their plot to the file unless the file is explicitly closed β€” either with a change of output device, or a call to reset, restart, or close. This is because those devices support multipage output and also require an end-of-file marker to close the file. Don't get caught out bestie 😭

πŸ“Š Plotting examples

✨ A simple example

my $win = gpwin('x11');
$win->plot( sin(xvals(45)) * 3.14159/10 );

Here we're just plotting a simple function, no biggie. The default plot style is a line, and line plots take a 2-tuple (X and Y values). Since we only supplied one element, plot() understands it to be the Y value (abscissa) of the plot, and it supplies value indices as X values β€” so we get a plot of just over 2 cycles of the sine wave over an X range across X values from 0 to 44. Iconic.

🌸 A not-so-simple example

$win = gpwin('x11');
$pi = 3.14159;
$win->plot( {with => line}, xvals(10)**2, xvals(10),
            {with => circles}, 2 * xvals(50), 2 * sin(xvals(50) * $pi / 10), xvals(50)/20
 );

This plots sqrt(x) in an interesting way, and overplots some circles of varying size. The line plot accepts a 2-tuple, and we supply both X and Y. The circles plot accepts a 3-tuple: X, Y, and R. The way that threading just works 🧚

πŸ’« A complicated example:

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

gplot( {trid => 1, title => 'double helix',cbr=>[0,1]},
      {with => 'linespoints',
       pointsize=>'variable',
       pointtype=>2,
       palette=>1,
       legend => ['spiral 1','spiral 2'],
       cdim=>1},
      pdl( cos($theta), -cos($theta) ),       # x
      pdl( sin($theta), -sin($theta) ),       # y
      $z,                                     # z
      (0.5 + abs(cos($theta))),               # pointsize
      sin($theta/3),                          # color
      { with=>'points',
        pointsize=>'variable',
        pointtype=>5,
        palette=>0
      },
      zeroes(6),                         # x
      zeroes(6),                         # y
      xvals(6),                          # z
      xvals(6)+1                         # point size
);

This is a 3d plot with variable size and color. There are 5 values in the tuple. The first 2 ndarrays have dimensions (N,2); all the other ndarrays have a single dimension. The cdim=>1 specifies that each column of data should be one-dimensional. So 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. Omitting the cdim curve option would yield a 201x2 grid with the linespoints plotstyle, rather than two separate curves. Subtle but crucial, iykyk πŸ’…

In addition to the threaded pair of linespoints curves, there are six variable size points plotted as filled squares, as a secondary curve.

Plot options are passed in in two places: as a leading hash ref, and as a trailing hash ref. Any other hash elements or hash refs must be curve options.

Curves are delimited by non-data arguments. After the initial hash ref, curve options for the first curve (the threaded pair of spirals) are passed in as a second hash ref. The curve's data arguments are ended by the first non-data argument β€” that's the hash ref with the curve options for the second curve.


πŸ”§ FUNCTIONS

gpwin

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

gpwin is the PDL::Graphics::Gnuplot exported constructor. It's exported by default and it's a synonym for new PDL::Graphics::Gnuplot(...). If you give it no arguments at all, it creates a plot object with the default terminal settings for your gnuplot. You can also hand it the name of a Gnuplot terminal type (e.g. 'x11') plus some terminal and output options (peep output). 🫢

new

$w = new PDL::Graphics::Gnuplot;
$w->plot( @plot_args );
#
# Specify plot options alone
$w = new PDL::Graphics::Gnuplot( {%plot_options} );
#
# Specify device and device options (and optional default plot options)
$w = new PDL::Graphics::Gnuplot( device, %device_options, {%plot_options} );
$w->plot( @plot_args );

Creates a PDL::Graphics::Gnuplot persistent plot object, and connects it to gnuplot. It's giving committed relationship πŸ’–

For convenience, you can specify the output device and its options right here in the constructor. Because different gnuplot devices accept different options, you must specify a device if you want to specify any device configuration options (such as window size, output file, text mode, or default font).

If you don't specify a device type, then the Gnuplot default device for your system gets used. You can set that with an environment variable (go check the Gnuplot documentation).

Gnuplot uses the word "terminal" for output devices; you can see a list of terminals supported by PDL::Graphics::Gnuplot by invoking PDL::Graphics::Gnuplot::terminfo() (for example in the perldl shell).

For convenience, you can provide default plot options here too. If the last argument to new() is a trailing hash ref, it's treated as plot options.

After you've created an object, you can change its terminal/output device with the output method, which is useful for (e.g.) throwing up an interactive plot and then sending it to a hardcopy device. See output for a description of terminal options and how to format them.

Normally, the object connects to the command gnuplot in your path, using the Alien::Gnuplot module. If you need to specify a binary other than this default, check the Alien::Gnuplot documentation.

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

output

$window->output( $device );
$window->output( $device, %device_options );
$window->output( $device, %device_options, {plot_options} );
$window->output( %device_options, {plot_options} );
$window->output( %device_options );

Sets the output device and options for a Gnuplot object. If you omit the $device name, then you get the gnuplot default device (generally x11, wxt, or aqua, depending on platform). Ngl that's kinda convenient.

You can control the output device of a PDL::Graphics::Gnuplot object on the fly. That's useful, for example, to replot several versions of the same plot to different output devices (interactive and hardcopy). So many vibes, so little time.

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

size

Okay so most drivers support a size option and it does exactly what it says on the tin β€” it sets how big your output plotting surface is gonna be. πŸŽ€

The format is [$width, $height, $unit]. The trailing unit string is optional but bestie, please include it, because the default unit of length literally changes from device to device and it will ghost you. πŸ™ˆ

That unit string can be in, cm, mm, px, char, or pt. Pixels are taken to be 1 point in size (72 pixels per inch) and dimensions are computed accordingly. Characters are taken to be 12 point in size (6 per inch). Math! Slay. πŸ’…

output

This option actually sets the object's output option for most terminal devices β€” and that changes the file your plot is gonna get written to. πŸ¦‹

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 instead (e.g. window in the X11 terminal). In the Gnuplot manual this is described as a "plot option", but here it's treated as a setup variable and parsed with the setup/terminal options in the constructor. Not me being quirky, that's just how it is. ✨

If you don't specify an output device, plots will go to sequentially-numbered files of the form Plot-<n>.<suf> in your current working directory. And in that case, PDL::Graphics::Gnuplot will report (on STDERR) where the plot ended up. So you'll never lose your babies. πŸ₯Ή

enhanced

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, or to a true value for enhanced text (which includes LaTeX-like markup for super/sub scripts and fonts). Iconic either way. πŸ‘‘

aa

For certain pixel-grid terminals (currently only pncairo and png, as of v2.012), you can specify an antialiasing factor for the output. πŸ”₯

The output is rendered oversized by a factor of aa, then scaled down using PDL::Transform. Fixed font sized, line widths, and point sizes are autoscaled β€” but you must handle variable ones explicitly. No one else is gonna do it for you, bestie.

Antialiasing is done in the gamma=2.2 approximation, to match the sRGB coding that most pixel image files use. (See PDL::Transform::Color for more information).


For a brief description of the terminal 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. Short queen behavior. πŸ’…


close

$w=gpwin();
$w->plot(xvals(5));
$w->close;

Close gnuplot process (actually just a synonym for restart) 🫢

Some of the gnuplot terminals (e.g. pdf) don't write out a file promptly. The close method closes the associated gnuplot subprocess, forcing the file to be written out. It is implemented as a simple restart operation.

The object preserves the plot state, so replot and similar methods still work with the new subprocess. Thank u object for not throwing away your progress. 😭


restart

$w->restart();
PDL::Graphics::Gnuplot::restart();

Restart the gnuplot backend for a plot object πŸ”„

Occasionally the gnuplot backend can get into an unknown state. restart kills the gnuplot backend and starts a new one, preserving state in the object. (i.e. replot and similar functions work even with the new subprocess). We love a comeback era. ✨

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


reset

$w->reset()

Clear state from the gnuplot backend 🧹

Clears all plot option state from the underlying object. All plot options except terminal, termoptions, output, and multiplot are cleared. This is similar to the reset command supported by gnuplot itself, and in fact it also causes a reset to be sent to gnuplot.

So those four survivors get to stay. Everything else? Gone. Periodt. πŸ’€

options

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

Set/get persistent plot options for a plot object πŸ’–

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.


plot_generate

Called with the same arguments as plot, it returns the text that would be sent to Gnuplot. Exportable. Added in 2.025. Lowkey a peek behind the curtain. πŸ™ˆ


gplot

Plot method exported by default (synonym for PDL::Graphics::Gnuplot::plot) 🌈


plot

This is the main plotting routine in PDL::Graphics::Gnuplot. The moment. The main character. πŸ‘‘

Each plot() call creates a new plot from whole cloth, either creating or overwriting the output for that device.

If you want to add features to an existing plot, use replot.

plot() understands the PDL bad value mechanism. Bad values are omitted from the plot. Gone but not forgotten. πŸ•ŠοΈ

$w=gpwin();
$w->plot({temp_plot_options},                 # optional
     curve_options, data, data, ... ,      # curve_options are optional for the first plot
     curve_options, data, data, ... ,
      {temp_plot_options});

Most of the arguments are optional. (Iconic of her, honestly.)

All of the extensive array of gnuplot plot styles are supported, including images and 3-D plots. No cap. πŸ”₯

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

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

You can pass plot options into plot as either a leading or trailing hash ref, or both. If you pass both, the trailing hash ref is parsed last and overrides the leading hash. Last one in wins, bestie. πŸ’…

For debugging and curiosity purposes, the last plot command issued to gnuplot is maintained in a package global: $PDL::Graphics::Gnuplot::last_plotcmd, and also in each object as the {last_plotcmd} field.


replot

Replot the last plot (possibly with new arguments). πŸ”

replot is similar to gnuplot's replot command β€” it allows you to regenerate the last plot made with this object. You can change the plot by adding new elements to it, modifying options, or even (with the device method) changing the output device. replot takes the same arguments as plot.

If you give no arguments at all (or only a plot object) then the plot is simply redrawn. If you give plot arguments, they are added to the new plot exactly as if you'd included them in the original plot element list, and maintained for subsequent replots.

(Compare to 'markup').


markup

Add ephemeral markup to the last plot. πŸŽ€

markup works exactly the same as replot, except that any new arguments are not added to the replot list β€” so you can add temporary markup to a plot and regenerate the plot later without it. It's giving guest appearance, not main cast. ✨


plot3d

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


splot

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


lines

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


points

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


image

Displays an image (either greyscale or RGB). Shorthand for plot(globalwith => 'image', ...) πŸ–ΌοΈ


imag

Synonym for image, for people who grew up with PDL::Graphics::PGPLOT and can't remember the closing 'e' 😭


fits

Displays a FITS image. Synonym for plot(globalwith => 'fits', ...). ⭐


multiplot_generate

Called with the same arguments as multiplot, it returns the text that would be sent to Gnuplot. Added in 2.025. πŸ”


multiplot

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

$w->multiplot(layout=>[2,2,"columnsfirst"]);
$w->plot({title=>"points"},with=>"points",$a,$b);
$w->plot({title=>"lines"}, with=>"lines", $a,$b);
$w->multiplot_next; # with Gnuplot 4.7+
$w->plot({title=>"image"}, with=>"image", $a->(*1) * $b );
$w->end_multi();

Plot multiple plots into a single page of output. 🎨

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.

Heads up bestie: 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. So don't. πŸ™…β€β™€οΈ

The options hash will accept:

layout - define a regular grid of plots to multiplot

layout should be followed by an ARRAY 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. Yes, dog. I am not kidding. 🐢

title - define a title for the entire page

title should be followed by a single scalar containing the title string. Name your page, queen. πŸ‘‘

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

scale takes either a scalar or an array 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. Stretch, bestie. πŸ’…

offset - offset each plot from its grid origin

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


multiplot_next_generate

Called with the same arguments as multiplot_next, it returns the text that would be sent to Gnuplot. Exportable. Added in 2.025. πŸ“¨


multiplot_next

Skip one plot. Added in 2.025. Requires Gnuplot 4.7+. ⏭️


end_multi_generate

Called with the same arguments as end_multi, it returns the text that would be sent to Gnuplot. Exportable. Added in 2.025. πŸ“¨


end_multi

$w=gpwin();
$w->multiplot(layout=>[2,1]);
$w->plot({title=>"points"},with=>'points',$a,$b);
$w->plot({title=>"lines"},with=>"lines",$a,$b);
$w->end_multi();

Ends a multiplot block (i.e. a block of plots that are meant to render to a single page). Closing the group chat, but make it art. πŸ™Œ


read_mouse

($x,$y,$char,$modstring) = $w->read_mouse($message);
$hash = $w->read_mouse($message);

Get a mouse click or keystroke from the active interactive plot window. πŸ–±οΈ

For interactive devices (e.g. x11, wxt, aqua), read_mouse lets you accept a keystroke or mouse button input from the gnuplot window. In list context, it returns four arguments containing the reported X, Y, keystroke character, and modifiers packed in a string. In scalar context, it returns a hash ref containing those things.

read_mouse blocks execution for input, but responds gracefully to interrupts. So it waits, but it's polite about it. 😌

read_polygon

$points = $w->read_polygon(%opt)

Read in a polygon by accepting mouse clicks. The polygon is returned as a 2xN PDL of ($x,$y) values in scientific units. Acceptable options are:

  • message β€” what to print before collecting points.

There are some printf-style escapes for the prompt:

  • %c β€” expands to "an open" or "a closed"
  • %n β€” number of points currently in the polygon
  • %N β€” number of points expected for the polygon
  • %k β€” list of all keys accepted
  • "%%" β€” a literal %
  • prompt β€” what to print to prompt the user for the next point. Uses the exact same escapes as message (yes bestie, same menu πŸ’…).
  • n_points β€” number of points to accept (or 0 for indefinite).

With a 0 value, points are accepted until the user presses q or ESC on the keyboard while the graph has focus. With any other value, points are accepted until that happens or until the number of points is at least n_points.

  • actions β€” hash of callback code refs indexed by character for action.

You can optionally call a callback routine when any particular character is pressed. The actions table is a hash ref whose keys are characters and whose values are either code refs (to be called on the associated keypress) or array refs containing a short description string followed by a code ref. Non-printable characters (e.g. ESC, BS, DEL) are accessed via a hash followed by a three digit decimal ASCII code β€” e.g. "#127" for DEL. Button events are indexed with the strings "BUTTON1", "BUTTON2", and "BUTTON3", and modifications must be entered as well for shift, control, and

ok so the source text literally trails off right there β€” not me catching the docs mid-sentence 😭 anyway, moving on πŸ’–

The code ref receives the arguments ($obj, $c, $poly,$x,$y,$mods), where:

  • $obj is the plot object
  • $c is the character (or "BUTTON"n"" string),
  • $poly is a scalar ref; $$poly is the current polygon before the action,
  • $x and $y are the current scientific coordinates, and
  • $mods is the modifier string.
You can't override the 'q' or '#027' (ESC) callbacks. You can override the BUTTON1 and DEL callbacks β€” and that could lowkey stop the user from entering points at all! Do that with caution, bestie. 🫣
  • closed β€” (default false): generate a closed polygon.

This works by duplicating the initial point at the end of the point list. Iconic behaviour honestly. ✨

  • markup β€” (default 'linespoints'): style to use to render the polygon on the fly.

If this is set to a true value, it should be a valid with specifier (curve option). The routine will call markup after each click.


pause_until_close πŸ’œ

$w->pause_until_close;

Wait until the active interactive plot window is closed β€” like, by clicking the close button, or hitting the close key-binding, which defaults to "q".

pause_until_close blocks execution until the close event. So yeah, it just sits there vibing until you shut the window. No cap. πŸ¦‹


terminfo ✨

use PDL::Graphics::Gnuplot qw/terminfo/;
terminfo();        # print info about all known terminals
terminfo 'aqua';   # print info about the aqua terminal

$w = gpwin();
$w->terminfo();

Print out information about gnuplot terminals and their custom option syntax.

The terminfo routine is a reference tool to describe the Gnuplot terminal types and the options they accept. It's mainly useful in interactive sessions. It outputs information directly to the terminal β€” no return value to catch, she just yaps straight onto your screen. πŸ“’


COMPATIBILITY 🌈

Everything should work on all platforms that support Gnuplot and Perl. Currently, MacOS, Fedora and Debian Linux, Cygwin, and Microsoft Windows (under both Active State Strawberry Perl) have been tested to work β€” although the interprocess control link is not as reliable under Microsoft Windows as under POSIX systems. 😬

Please report successes or failures on other platforms to the authors. A transcript of a failed run with {tee => 1} would be most helpful β€” that's the good stuff, feed them the receipts bestie πŸŽ€


REPOSITORY πŸ’š

<https://github.com/drzowie/PDL-Graphics-Gnuplot>


AUTHOR πŸ“

Craig DeForest, "<craig@deforest.org>" and Dima Kogan, "<dima@secretsauce.net>"


STILL TO DO ⭐

some plot and curve options need better parsing:

  • labels need attention (plot option labels) They need to be handled as hashes, not just as array refs. Also, they don't seem to be working with timestamps. Further, deeply nested options (e.g. "at" for labels) need attention.
  • new plot styles The "boxplot" plot style (new to gnuplot 4.6?) requires a different using syntax and will require some hacking to support.
the to-do list is giving "we'll get to it bestie, we promise" and honestly? respect πŸ™ˆ

Copyright 2011-2013 Craig DeForest and Dima Kogan

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 included with the Perl language.

See http://dev.perl.org/licenses/ for more information.


and that's the whole page, bestie!! πŸ₯³ this was PDL::G...nuplot(3pm) from perl v5.42.3, dated 2026-08-19, straight out of the User Contributed Perl Documentation β€” go plot something gorgeous, you ate πŸ’…πŸ’–βœ¨

πŸ“¦ where this page comes from