Window(3pm)
β¨ NAME β¨
okay so Window(3pm) is this page, bestie, and the actual package is PDL::Graphics::PGPLOT::Window β A OO interface to PGPLOT windows. periodt π
π SYNOPSIS π
pdl> use PDL::Graphics::PGPLOT::Window
pdl> $win = pgwin(Device => '/xs');
pdl> $x = pdl [1..100]
pdl> $y = sqrt($x)
pdl> $win->line($y)
pdl> $win->hold()
pdl> $c = sin($x/10)*2 + 4
pdl> $win->line($c)
In the following documentation the commands are not shown in their OO versions. This is for historical reasons and should not cause too much trouble. iykyk π¦
π DESCRIPTION π
This package offers a OO interface to the PGPLOT plotting package. It is intended to replace the traditional interface in PDL::Graphics::PGPLOT and contains interfaces to a large number of PGPLOT routines. Below the usage examples for each function tend to be given in the non-OO version for historical reasons. This will slowly be changed, but in the meantime refer to the section on OO-interface below to see how to convert the usage information below to OO usage (it is totally trivial). not me loving a legacy interface π
PDL::Graphics::PGPLOT::Window is an interface to the PGPLOT graphical libraries. It currently supports PGPLOT-5.2 and PGPLOT-5.2-cd2. The -cd2 version includes RGB output and anti-aliasing. slay π
π High-level plotting commands π
imagβ Display an image (usespgimag/pggray/pgrgbias appropriate)fits_imagβ Display a FITS image in scientific coordinatescontβ Display image as contour mapfits_contβ Display a FITS image in scientific coordinates as a contour mapvectβ Display 2 images as a vector fieldfits_vectβ Display 2 FITS images in sci. coordinates as a vector fieldctabβ Load an image colour tablectab_infoβ Get information about currently loaded colour tablelineβ Plot vector as connected pointstlineβ Plot a collection of vectors as lineslinesβ Plot a polyline, multicolor vector [broadcastable]pointsβ Plot vector as pointstpointsβ Plot a collection of vectors as points [broadcastable]errbβ Plot error barsbinβ Plot vector as histogram (e.g.bin(hist($data)))hi2dβ Plot image as 2d histogram (not very good IMHO...)tcircleβ Plot vectors as circles [broadcastable]label_axesβ Print axis titleslegendβ Create a legend with different texts, linestyles etc.
π Low-level plotting commands π
arrowβ Draw an arrowpolyβ Draw a polygonrectangleβ Draw a rectangletextβ Write text in the plot areacursorβ Interactively read cursor positions.circleβ Draw a circleellipseβ Draw an ellipse.
π¦ Device manipulation commands π¦
newβ Construct a new output devicepgwinβ Exported hook tonew()closeβ Close a PGPLOT output device.holdβ Hold current plot window range - allows overlays etc.releaseβ Release back to freshly autoscaling for each command.heldβ Indicates whether the current window is held.focusβ Set focus to the given device.eraseβ Erase the current window (or panel).optionsβ Get the options set for the present output device.idβ The ID for the device.deviceβ The device type.nameβ The window name.
Notes: $transform for image/cont etc. is used in the same way as the TR() array in the underlying PGPLOT FORTRAN routine but is, fortunately, zero-offset. The transform() routine can be used to create this ndarray. zero-offset? we love to see it π
For completeness: The transformation array connect the pixel index to a world coordinate such that:
X = tr[0] + tr[1]*i + tr[2]*j
Y = tr[3] + tr[4]*i + tr[5]*j
π§ Variable passing and extensions π§
In general variables are passed to the pgplot routines by using "get_dataref" to get the reference to the values. Before passing to pgplot routines however, the data are checked to see if they are in accordance with the format (typically dimensionality) required by the PGPLOT routines. This is done using the routine "checkarg" (internal to PGPLOT). This routine checks the dimensionality of the input data. If there are superfluous dimensions of size 1 they will be trimmed away until the dimensionality is correct. Example:
Assume an ndarray with dimensions (1,100,1,1) is passed to "line", which expects its inputs to be vectors. "checkarg" will then return an ndarray with dimensions (100). If instead the same ndarray was passed to "imag", which requires 2D ndarrays as output, "checkarg" would return an ndarray with dimensionality (100, 1) (Dimensions are removed from the start)
Thus, if you want to provide support for another PGPLOT function, the structure currently look like this (there are plans to use the Options package to simplify the options parsing):
# Extract the hash(es) on the commandline
($arg, $opt)=_extract_hash(@_);
<Check the number of input parameters>
<deal with $arg>
checkarg($x, 3); # For a hypothetical 3D routine.
catch_signals {
...
pgcube($n, $x->get_dataref);
};
1;
(the catch_signals block prevents problems with the perl-PGPLOT interface if the user hits Ctrl-C during an operation). protect ya code π«Ά
πΈ Setting options πΈ
All routines in this package take a hash with options as an optional input. This options hash can be used to set parameters for the subsequent plotting without going via the PGPLOT commands.
This is implemented such that the plotting settings (such as line width, line style etc.) are affected only for that plot, any global changes made, say, with pgslw() are preserved. Some modifications apply when using the OO interface, see below. per-plot glow-up, not a global reset β¨
π Alphabetical listing of standard options π
The following options are always parsed. Whether they have any importance depend on the routine invoked - e.g. line style is irrelevant for "imag", or the "justify" option is irrelevant if the display is on 'hold'. This is indicated in the help text for the commands below.
The options are not case sensitive and will match for unique substrings, but this is not encouraged as obscure options might invalidate what you thought was a unique substring. lowkey chaotic π
In the listing below examples are given of each option. The actual option can then be used in a plot command by specifying it as an argument to the function wanted (it can be placed anywhere in the command list).
E.g:
$opt={COLOR=>2};
line $x, $y, $opt; # This will plot a line with red color
If you are plotting to a hardcopy device then a number of options use a different name:
HardLW instead of LineWidth
HardCH instead of CharSize
HardFont instead of Font
HardAxisColour instead of AxisColour
HardColour instead of Colour
[although I'm not sure when HardColour is actually used]
alignβ If"pix"is set, then images and plots are not stretched to fill the plot area. the"align"string tells how to align them within the available area.'L'and'R'shove the plot against the left and right edges, respectively;'B'and'T'shove the plot against the bottom and top edges. The default is to center the image. e.g.'BL'puts the image on the bottom left corner, while'CT'centers the image horizontally while placing it at the top of the available plot area. This defaults to'BT'for non-justified images, to'CC'for justified images. vibe check: aligned πarrowβ This options allows you to set the arrow shape, and optionally size for arrows for thevectroutine. The arrow shape is specified as a hash with the keyFSto set fill style,ANGLEto set the opening angle of the arrow head,VENTto set how much of the arrow head is cut out andSIZEto set the arrowsize.
The following
$opt = {ARROW => {FS=>1, ANGLE=>60, VENT=>0.3, SIZE=>5}};
will make a broad arrow of five times the normal size. big arrow energy π₯
Alternatively the arrow can be specified as a set of numbers corresponding to an extension to the syntax for pgsah. The equivalent to the above is
$opt = {ARROW => pdl([1, 60, 0.3, 5})};
For the latter the arguments must be in the given order, and if any are not given the default values of 1, 45, 0.3 and 1.0 respectively will be used.
arrowsizeβ The arrowsize can be specified separately using this option to the options hash. It is useful if an arrowstyle has been set up and one wants to plot the same arrow with several sizes. Please note that it is not possible to set arrowsize and character size in the same call to a plotting function. This should not be a problem in most cases. one size does not fit all, bestie β¨
$opt = {ARROWSIZE => 2.5};
axisβ Set the axis value (see"env"). If you pass in a scalar you set the axis for the whole plot. You can also pass in an array ref for finer control of the axes.
If you set the option to a scalar value, you get one of a few standard layouts. You can specify them by name or by number:
EMPTY (-2) draw no box, axes or labels
BOX (-1) draw box only
NORMAL (0) draw box and label it with coordinates
AXES (1) same as NORMAL, but also draw (X=0,Y=0) axes
GRID (2) same as AXES, but also draw grid lines
LOGX (10) draw box and label X-axis logarithmically
LOGY (20) draw box and label Y-axis logarithmically
LOGXY (30) draw box and label both axes logarithmically
When using logarithmic axes ("LOGX", "LOGY" and "LOGXY") you normally need to log the data yourself, e.g.
line $x->log10, $y, {axis=>'LOGX'};
For your convenience you can put PDL::Graphics::PGPLOT into autolog mode. In this mode a call to "line" or "points" will log the data for you and you can pass in the unmodified data, e.g.
autolog(1); # enable automatic logarithm calculation
line $x, $y, {axis=>'LOGX'}; # automatically displays logged x data
You can use the function interface to enable autologging:
autolog(1);
or use it with a window reference (mode switching on a per window basis)
$win->autolog(1);
"autolog" without arguments returns the current autolog setting (0=off, 1=on).
If you set the "AXIS" option to an array ref, then you can specify the box/axis options separately for the horizontal (ordinate; X coordinate; 0th element) and vertical (abscissa; Y coordinate; 1st element)) axes. Each element of the array ref should contain a PGPLOT format string. Presence or absence of specific characters flags particular options. For normal numeric labels, the options are:
Aβ draw the axis for this dimension, periodt πBβ draw the bottom (X) or left (Y) edge of the frameCβ draw the top (X) or right (Y) edge of the frameGβ draw the Grid of vertical (X) or horizontal (Y) lines πΈοΈIβ Invert the ticks, bestie: draw them outside the plot instead of insideLβ Label the axis Logarithmically πPβ Extend ("Project") the major tick marks outside the boxMβ Numeric labels go in the alternate place β above (X) or to the right (Y) of the viewportNβ Numeric labels go in the usual spot β below (X) or to the left (Y) of the viewportTβ Draw major tick marks at the major coordinate intervalSβ Draw minor tick marks (subticks)Vβ Orient the numeric labels Vertically. Only works for Y, just so you know. (The default is to write them parallel to the axis.)1β Force decimal labelling instead of letting it choose automatically2β Force exponential labeling instead of letting it choose automatically
If you don't specify any axis value at all, the default is ['BCNST','BCNST'] for plots and ['BCINST','BCINST'] for images. (These list ref elements get handed straight on to the low-level PGPLOT routines, no cap.)
On top of all that, you can tell your axis labels to print as days, hours, minutes and seconds β which is chef's kiss for julian dates and delta-t, or for angular quantities. You do it by setting extra character flags on the axis in question:
Xβ Use HH MM SS.S time labeling rather than conventional numeric labels. The ordinate is in seconds. Hours roll over at 24. β°Yβ Like'X', but the hour field runs past 24 if it needs toZβ Like'X', but with a days field too (only shown where it's nonzero)Hβ Label the numbers with superscript d, h, m, and s symbolsDβ Label the numbers with superscript o, ', and '' symbolsFβ Omit the first (lowest/leftmost) label; so useful for tight layouts πOβ Omit leading zeroes in numbers under 10 (like" 3h 3m 1.2s"rather than"03h 03m 01.2s")
So for example, to plot a numeric quantity versus Julian day of the year in a standard boxed plot with tick marks, you can use ["BNCSTZHO","BCNST"]. Slay. π
π border π
Normally the limits are chosen so the plot just fits. With this option you can increase (or decrease) those limits by either a relative amount (a fraction of the original axis width) or an absolute amount. Either hand it a hash array where the keys are "TYPE" (set to 'relative' or 'absolute') and "VALUE" (the amount to change the limits by), or just set it to 1, which is equivalent to
BORDER => { TYPE => 'rel', VALUE => 0.05 }
π¦ charsize π¦
Set the character/symbol size as a multiple of the standard size.
$opt = {CHARSIZE => 1.5}
The HardCH option should be used if you are plotting to a hardcopy device.
π colour (or color) π
Set the colour to be used for the subsequent plotting. You can specify it as a number, and the most used colours can also be specified with a name, according to the following table (note that this only works for the default colour map):
0 - WHITE 1 - BLACK 2 - RED 3 - GREEN 4 - BLUE
5 - CYAN 6 - MAGENTA 7 - YELLOW 8 - ORANGE 14 - DARKGRAY
16 - LIGHTGRAY
But okay, there's a much more flexible mechanism for colour. You can set the colour as a 3 or 4 element anonymous array (or ndarray) that gives the RGB colours. If the array has four elements, the first element is taken to be the colour index to change. For normal work you might want to just use a 3 element array with R, G and B values and let the package deal with the details. The R, G and B values go from 0 to 1.
On top of that, the package will also try to interpret non-recognised colour names using the default X11 lookup table, normally using the "rgb.txt" that came with PGPLOT.
For more details on the handling of colour it is best that the user consults the PGPLOT documentation. Further details on the handling of colour can be found in the documentation for the internal routine "_set_colour".
The HardColour option should be used if you are plotting to a hardcopy device [this may be untrue?]. π
β¨ diraxis β¨
This sets the direction of the axes of a plot or image, for when you don't explicitly set them with the XRange and YRange options. It's especially handy when you want (for example) to put long wavelengths (larger numbers) on the left hand side of your plot, or when you want to plot an image in (RA,dec) coordinates.
You can use either a scalar or a two-element perl array. If you set it to 0 (the default) then PDL will guess which direction you want to go. If you set it to a positive number, the axis will always increase to the right. If you set it to a negative number, the axis will always increase to the left.
For example, [0,0] is the default, which is usually right. [1,1] tells PGPLOT to always increase the axis values up and to the right. For a plot of intensity (y-axis) versus wavelength (x-axis) you could say [-1,1].
This option is really only useful if you want to allow autoranging but need to set the direction that the axis goes. If you use the ranging options ("XRange" and "YRange"), you can change the direction by changing the order of the maximum and minimum values. That direction will override "DirAxis".
π filltype π
Set the fill type to be used by "poly", "circle", "ellipse", and "rectangle". The fill can either be specified using numbers or a name, according to the following table, where the recognised name is shown in capitals β it is case-insensitive, but the whole name must be specified.
1 - SOLID
2 - OUTLINE
3 - HATCHED
4 - CROSS_HATCHED
$opt = {FILLTYPE => 'SOLID'};
(see below for an example of hatched fill π)
π«Ά font π«Ά
Set the character font. This can either be specified as a number following the PGPLOT numbering, or by name as follows (name in capitals):
1 - NORMAL
2 - ROMAN
3 - ITALIC
4 - SCRIPT
(Note that in a string, the font can be changed using the escape sequences "\fn", "\fr", "\fi" and "\fs" respectively)
$opt = {FONT => 'ROMAN'};
gives the same result as
$opt = {FONT => 2};
The HardFont option should be used if you are plotting to a hardcopy device.
π hatching π
Set the hatching to be used if either fillstyle 3 or 4 is selected (see above). The specification is similar to the one for specifying arrows. The arguments for the hatching are either given using a hash with the key ANGLE to set the angle that the hatch lines will make with the horizontal, SEPARATION to set the spacing of the hatch lines in units of 1% of "min(height, width)" of the view surface, and PHASE to set the offset of the hatching. Alternatively this can be specified as a 1x3 ndarray "$hatch=pdl[$angle, $sep, $phase]".
$opt = {FILLTYPE => 'HATCHED',
HATCHING => {ANGLE=>30, SEPARATION=>4}};
Can also be specified as
$opt = {FILL=> 'HATCHED', HATCH => pdl [30,4,0.0]};
For another example of hatching, see "poly".
π§ justify π§
If "justify" is set true, then the plot axes are shrunk to fit the plot or image, and it specifies the aspect ratio of pixel coordinates in the plot or image. Setting justify=>1 will produce a correct-aspect-ratio, shrink-wrapped image or plot; setting justify=>0.5 will do the same thing but with a short and fat plot. The difference between "justify" and "pix" is that "pix" does not affect the shape of the axes themselves.
π linestyle π
Set the line style. This can either be specified as a number following the PGPLOT numbering:
1 - SOLID line
2 - DASHED
3 - DOT-DASH-dot-dash
4 - DOTTED
5 - DASH-DOT-DOT-dot
or using a name (as given in capitals above). So the following two specifications both specify the line to be dotted:
$opt = {LINESTYLE => 4};
$varopt = {LINESTYLE => 'DOTTED'};
The names are not case sensitive, but the full name is required.
β linewidth β
Set the line width. It is specified as an integer multiple of 0.13 mm.
$opt = {LINEWIDTH => 10}; # A rather fat line
The HardLW option should be used if you are plotting to a hardcopy device.
π pitch π
Sets the number of data pixels per inch on the output device. You can set the "unit" (see below) to change this to any other PGPLOT unit (millimeters, pixels, etc.). Pitch is device independent, so an image should appear exactly the same size (e.g. "Pitch=>100" is 100 dpi) regardless of output device.
π« pix π«
Sets the pixel aspect ratio height/width. The height is adjusted to the correct ratio, while maintaining any otherwise-set pitch or scale in the horizontal direction. Larger numbers yield tall, skinny pixels; smaller numbers yield short, fat pixels.
πΈ scale πΈ
Sets the number of output display pixels per data pixel. You can set the "unit" (see below) to change this to number of PGPLOT units (inches, millimeters, etc.) per data pixel. "scale" is deprecated, as it is not device-independent; but it does come in handy for quick work on digital displays, where aliasing might otherwise interfere with image interpretation. For example, "scale=>1" displays images at their native resolution.
π Panel π
It is possible to define multiple plot ``panels'' within a single window (see the NXPanel and NYPanel options in the constructor). You can explicitly set in which panel most plotting commands occur by passing either a scalar or an array ref into the "Panel" option. There is also a panel method, but its use is deprecated because of a wart with the PGPLOT interface.
π plotting & imaging range π
Explicitly set the plot range in x and y. X-range and Y-range are set separately via the aptly named options "XRange" and "YRange". If omitted, PGPLOT selects appropriate defaults (minimum and maximum of the data range in general). These options are ignored if the window is on hold.
line $x, $y, {xr => [0,5]}; # y-range uses default
line $x, $y, {XRange => [0,5], YRange => [-1,3]}; # fully specified range
imag $im, {XRange => [30,50], YRange=>[-10,30]};
fits_imag $im, {XRange=>[-2,2], YRange=>[0,1]};
Imaging needs a lil bit of thought tho, like if you don't wanna lose a pixel off the edge of your image π Pixels are value-centered, meaning they're centered on the coordinate whose value they represent, so the correct range to plot a whole 100x100 pixel image is "[-0.5,99.5]" on each axis. Iconic. Remember it.
π OBJECT-ORIENTED INTERFACE π
Okay bestie, this section is a quick lil tour of how you can use the PDL::Graphics::PGPLOT::Window package in an object-oriented (OO) way, and honestly why you'd even want to. Starting with the why, obvi π
Multiple windows
For the average user this is probably the most interesting reason to go OO β handling several open devices at the same time. If you have one variable for each plot device, it's just so much easier to send the right commands to the right device at the right time. That's the angle we're taking for the rest of this description. Periodt.
Coding and abstraction
At a more fundamental level, it's desirable to aim for a situation where you can have a generic plotting interface that gives you access to several plotting libraries β basically what PGPLOT does for different output devices. So in such a hypothetical package you'd say something like:
my $win1 = Graphics::new('PGPLOT', {Device => '/xs'});
my $win2 = Graphics::new('gnuplot', {Background => 'Gray'};
From a more practical point of view, this kind of abstraction also comes in handy when you're writing a large program package and you don't want to import routines nilly-willy β in that case an OO approach with method calls is a whole lot cleaner β¨
The pgwin exported constructor, arguably, breaks this philosophy; hopefully it will ``wither away'' when other compatible modules become available. We love a deprecated king π«Ά
Anyway, enough philosophizing, let's get down to Earth and give some examples of OO PGPLOT in action. As an example we'll take Odd (which happens to be a common Norwegian name) who is monitoring the birth of rabbits on O'Fib-o-nachy's farm (alternatively they could of course be monitoring processes or doing something entirely different, no judgment). Odd wants the user to be able to monitor both the birth rates and the accumulated number of rabbits and the spatial distribution of the births. Since these are logically different, they choose to have two windows open:
$rate_win = PDL::Graphics::PGPLOT::Window->new(Device => '/xw',
Aspect => 1, WindowWidth => 5, NXPanel => 2);
$area_win = PDL::Graphics::PGPLOT::Window->new(Device => '/xw',
Aspect => 1, WindowWidth => 5);
See the documentation for "new" below for a full overview of the options you can pass to the constructor. Bestie, read the docs, it's giving responsible π
Next, Odd wants to create plotting areas for subsequent plots and maybe show the expected theoretical trends:
$rate_win->env(0, 10, 0, 1000, {XTitle => 'Days', YTitle => '#Rabbits'});
$rate_win->env(0, 10, 0, 100, {Xtitle=>'Days', Ytitle => 'Rabbits/day'});
$area_win->env(0, 1, 0, 1, {XTitle => 'Km', Ytitle => 'Km'});
# And theoretical prediction.
$rate_win->line(sequence(10), fibonacci(10), {Panel => [1, 1]});
And that's basically it, slay. The commands should automatically focus the relevant window. Due to the limitations of PGPLOT though, this might lead you to plot in the wrong panel... π The package tries to be smart and do this correctly, but it might get it wrong at times. Not me defending a library's coping mechanism.
π STATE and RECORDING π
A new addition to the graphics interface is the ability to record plot commands. This is lowkey so useful when you create a nice-looking plot on the screen and then wanna re-create it on paper, for instance. Or if you wanna redo it with slightly changed variables. This is still under development and views on the interface are welcome, so speak up bestie π
The functionality is somewhat detached from the plotting functions described below, so I'll discuss them and their use right here.
Recording is off by default. To turn it on when you create a new device you can set the "Recording" option to true, or you can set the $PDL::Graphics::PGPLOT::RECORDING variable to 1. I recommend doing the latter in your ".perldlrc" file, at least, since you'll often have use for recording in the perldl or pdl2 script. Set it and forget it, fr fr.
Use of recording
The recording is meant to help you recreate a plot with new data, or onto a different device. The most typical situation is that you've created a beautiful plot on screen and now you want a Postscript file of it. In the dreary old world you'd have to go back and execute all the commands manually, but with this wonderful new contraption, the recorder, you can just replay your commands:
dev '/xs', {Recording => 1}
$x = sequence(10)
line $x, $x**2, {Linestyle => 'Dashed'}
$s = retrieve_state() # Get the current tape out of the recorder.
dev '/cps'
replay $s
This should result in a "pgplot.ps" file with a parabola drawn with a dashed line. Note the command "retrieve_state" which retrieves the current state of the recorder and returns an object (of type PDL::Graphics::State) that is used to replay commands later. Ate, no crumbs.
Controlling the recording
Like any self-respecting recorder, you can turn the recorder on and off using "turn_on_recording" and "turn_off_recording" respectively. Likewise you can clear the state using the "clear_state" command.
$w=PDL::Graphics::PGPLOT::Window->new(Device => '/xs');
$w->turn_on_recording;
$x=sequence(10); $y=$x*$x;
$w->line($x, $y);
$w->turn_off_recording;
$w->line($y, $x);
$w->turn_on_recording;
$w->line($x, $y*$x);
$state = $w->retrieve_state();
We can then replay $state and get a parabola and a cubic plot π¦
$w->replay($state);
Tips and Gotchas!
The data are stored in the state object as references to the real data. This leads to one good and one potentially bad consequence:
The good one is that you can create the plot and then subsequently redo the same plot using a different set of data. This is best explained by an example. Let's first create a simple gradient image and get a copy of the recording:
$im = sequence(10,10)
imag $im
$s=retrieve_state
Now that was a rather dull plot, and in reality we wanted to show an image using "rvals". Instead of re-creating the plot (which of course here would be the simplest option), we just change $im:
$im -= sequence(10,10)
$im += rvals(10,10)
Now replay the commands:
replay $s
And hey presto! A totally different plot β¨ Note however the trickery required to avoid losing reference to $im.
This takes us immediately to the major problem with the recording though. Memory leakage! π Since the recording keeps references to the data, it can keep data from being freed (zero reference count) when you expect it to be. For instance, in this example, we lose totally track of the original $im variable, but since there is a reference to it in the state, it will not be freed:
$im = sequence(1000,1000)
imag $im
$s = retrieve_state
$im = rvals(10,10)
Thus after the execution of these commands we still have a reference to a 1000x1000 array, which takes up a lot of memory... π
The solution is to call "clear" on the state variable:
$s->clear()
(This is done automatically if the variable goes out of scope.) I forsee this problem to be most acute when working on the "perldl" or "pdl2" command line, but since this is exactly where the recording is most useful, the best advice is just to be careful and call clear on state variables.
If you're working with scripts and use large images for instance, I would instead recommend that you do not turn on recording unless you need it. Protect your RAM bestie, it's the only one you've got π«Ά
π FUNCTIONS π
A more detailed listing of the functions and their usage follows. For all functions we specify which options take effect and what other options exist for the given function. The function descriptions below are all given for the non-OO usage for historical reasons, but since the conversion to an OO method is trivial there's no major need for concern. Whenever you see a function example of the form
Usage: a_simple_function($x, $y, $z [, $opt]);
and you wish to use the OO version, just let your mind read the above line as:
Usage: $win->a_simple_function($x, $y, $z [, $opt]);
where $win is a PDL::Graphics::PGPLOT::Window object. That is all. Simple as, iykyk.
Window control functions.
pgwin
Exported constructor for PGPLOT object/device/plot window.
Usage: pgwin($opt);
Usage: pgwin($option->$value,...);
Usage: pgwin($device);
Parameters are passed on to new() and can either be specified by hash reference or as a list.
See the documentation fo PDL::Graphics::PGPLOT::Window::new for details.
Because pgwin is a convenience function, you can specify the device by passing in a single non-ref parameter. For even further convenience, you can even omit the / in the device specifier, so these two lines deliver the same result:
$win = pgwin(gif);
$win = PDL::Graphics::PGPLOT::Window->new({Dev=>'/gif'});
new
Constructor for PGPLOT object/device/plot window.
Usage: PDL::Graphics::PGPLOT::Window->new($opt);
Usage: PDL::Graphics::PGPLOT::Window->new($option=>$value,...);
Options to new() can either be specified via a reference to a hash
$win = PDL::Graphics::PGPLOT::Window->new({Dev=>'/xserve',ny=>2});
or directly, as an array
# NOTE: no more {} !
$win = PDL::Graphics::PGPLOT::Window->new(Dev=>'/xserve',ny=>2);
The following lists the recognised options:
AspectRatioβ The aspect ratio of the image, in the sense vertical/horizontal. See the discussion on size setting.Deviceβ The type of device to use. The syntax of this is the one used by PGPLOT.Holdβ Hold the plot window so that subsequent plots can plot over existing plots. This can be adjusted with thehold()andrelease()methods.NXPanelβ The number of panels in the X-direction.NYPanelβ The number of panels in the Y-direction.Sizeβ Yet another way to identify the plot window size -- this takes a scalar or an array ref containing one, two, or three numbers. One number gives you a square window. Two gives you a rectangular window"(X,Y)". Three lets you specify the unit compactly (e.g."[<X>,<Y>,1]"for inches,"[<X>,<Y>,2]"for mm) but is deprecated in favor of using the"Unit"option. See the discussion on size setting.Unitβ bestie, this is the unit you use for size setting. PGPLOT acceptsinch,mm, orpixel. The default unit is inches for historical reasons (iykyk), but you can choose millimeters or (God forbid) pixels as well. String or numeric specifications are OK (0=normalized,1=inches,2=mm,3=pixels). Normalized units make no sense here and are not accepted. Ideally someone will one day hook this into the CPAN units parser so you can specify window size in rods or attoparsecs. πWindowNameβ the name to give to the window. No particular use is made of this at present. It would be great if it was possible to change the title of the window frame. πWindowWidthβ the width of the window in inches (or the specifiedUnit). See the discussion on size setting. β¨WindowXSizeandWindowYSizeβ the width and height of the window in inches (or the specifiedUnit). See the discussion on size setting. π¦
An important point to note is that the default values of most options can be specified by passing these to the constructor. All general options (common to several functions) can be adjusted in such a way, but function specific options can not be set in this way (this is a design limitation which is unlikely to be changed). π
Thus the following call will set up a window where the default axis colour will be yellow and where plot lines normally have red colour and dashed linestyle. Slay.
$win = PDL::Graphics::PGPLOT::Window->new(Device => '/xs',
AxisColour => 'Yellow', Colour => 'Red', LineStyle => 'Dashed');
Size setting: There are a gazillion ways to set window size, in keeping with TIMTOWTDI. In general you can get away with passing any unique combination of an <X> size, a <Y> size, and/or an aspect ratio. In increasing order of precedence, the options are: (Units, AspectRatio, WindowWidth, Window<X,Y>Size, Size).
So if you specify an AspectRatio and an X and a Y coordinate, the AspectRatio is ignored. Likewise, if you specify Units and a three-component Size, the Units option is ignored in favor of the numeric unit in the Size.
If you don't specify enough information to set the size of the window, you get the default pane size and shape for that device. π
close π
Close a plot window
Usage: $win->close()
Close the current window. This does not necessarily mean that the window is removed from your screen, but it does ensure that the device is closed.
A message will be printed to STDOUT giving the name of the file created if the plot was made to a hardcopy device and $PDL::verbose is true.
held π«Ά
Check if a window is on hold
$is_held = $win->held();
Function to check whether the window is held or not.
hold β¨
Hold the present window.
Usage: $win->hold()
Holds the present window so that subsequent plot commands overplots.
panel π
Switch to a different panel
$win->panel(<num>);
Move to a different panel on the plotting surface. Note that you will need to erase it manually if that is what you require.
This routine currently does something you probably don't want, and hence is deprecated for most use: if you say
$win->panel(1);
$win->imag($image);
then $image will actually be displayed in panel 2. That's because the main plotting routines such as line and imag all advance the panel when necessary. Instead, it's better to use the Panel option within plotting commands, if you want to set the panel explicitly.
release π
Release a plot window.
$win->release()
Release a plot window so that subsequent plot commands move to the next panel or erase the plot and create a new plot.
erase π
Erase plot
$win->erase($opt);
Erase a plot area. This accepts the option Panel or alternatively a number or array reference which makes it possible to specify the panel to erase when working with several panels.
Plotting functions π
env π
Define a plot window, and put graphics on 'hold'
$win->env( $xmin, $xmax, $ymin, $ymax, [$justify, $axis] );
$win->env( $xmin, $xmax, $ymin, $ymax, [$options] );
$xmin, $xmax, $ymin, $ymax are the plot boundaries. $justify is a boolean value (default is 0); if true the axes scales will be the same (see "justify"). $axis describes how the axes should be drawn (see "axis") and defaults to 0.
If the second form is used, $justify and $axis can be set in the options hash, for example:
$win->env( 0, 100, 0, 50, {JUSTIFY => 1, AXIS => 'GRID',
CHARSIZE => 0.7} );
In addition the following options can also be set for env:
PlotPositionβ the position of the plot on the page relative to the view surface in normalised coordinates as an anonymous array. The array should contain the lower and upper X-limits and then the lower and upper Y-limits. To place two plots above each other with no space between them you could do
$win->env(0, 1, 0, 1, {PlotPosition => [0.1, 0.5, 0.1, 0.5]});
$win->env(5, 9, 0, 8, {PlotPosition => [0.1, 0.5, 0.5, 0.9]});
Axis,Justify,Borderβ see the description of general options for these options.AxisColourβ set the colour of the coordinate axes.XTitle,YTitle,Title,Font,CharSizeβ axes titles and the font and size to print them.
label_axes π·οΈ
Label plot axes
$win->label_axes(<xtitle>, <ytitle>, <plot title>, $options);
Draw labels for each axis on a plot.
imag πΈ
Display an image (uses pgimag()/pggray() as appropriate)
$win->imag ( $image, [$min, $max, $transform], [$opt] )
NOTES
$transform for image/cont etc. is used in the same way as the TR() array in the underlying PGPLOT FORTRAN routine but is, fortunately, zero-offset. The transform() routine can be used to create this ndarray.
If $image is two-dimensional, you get a grey or pseudocolor image using the scalar values at each X,Y point. If $image is three-dimensional and the third dimension has order 3, then it is treated as an RGB true-color image via rgbi.
There are several options related to scaling. By default, the image is scaled to fit the PGPLOT default viewport on the screen. Scaling, aspect ratio preservation, and 1:1 pixel mapping are available. (1:1 pixel mapping is useful for avoiding display artifacts, but it's not recommended for final output as it's not device-independent.)
Here's an additional complication: the "pixel" stuff refers not (necessarily) to normal image pixels, but rather to transformed image pixels. That is to say, if you feed in a transform matrix via the TRANSFORM option, the PIX, SCALE, etc. options all refer to the transformed coordinates and not physical image pixels. That is a Good Thing because it, e.g., lets you specify plate scales of your output plots directly! See fits_imag for an example application. If you do not feed in a transform matrix, then the identity matrix is applied so that the scaling options refer to original data pixels.
To draw a colour bar (or wedge), either use the DrawWedge option, or the draw_wedge() routine (once the image has been drawn).
Options recognised:
ITFβ the image transfer function applied to the pixel values. It may be one of'LINEAR','LOG','SQRT'(lower case is acceptable). It defaults to'LINEAR'.MINβ sets the minimum value to be used for calculation of the color-table stretch.MAXβ sets the maximum value for the same.RANGEβ a more compact way to specifyMINandMAX, as a list: you can say"Range=>[0,10]"to scale the color table for brightness values between 0 and 10 in the iamge data.CRANGEβ image values betweenMINandMAXare scaled to an interval in normalized color domain space, on the interval[0,1], before lookup in the window's color table.CRANGElets you use only a part of the color table by specifying your own range -- e.g. if you say"CRange=>[0.25,0.75]"then only the middle half of the pseudocolor space will be used. (See the writeup onctab().)TRANSFORMβ the PGPLOT transform 'matrix' as a 6x1 vector for displayDrawWedgeβ set to 1 to draw a colour bar (default is 0)Wedgeβ see thedraw_wedge()routine
The following standard options influence this command:
AXIS, BORDER, JUSTIFY, SCALE, PIX, PITCH, ALIGN, XRANGE, YRANGE
To see an image with maximum size in the current window, but square pixels, say:
$win->imag( $x, { PIX=>1 } );
An alternative approach is to try:
$win->imag( $x, { JUSTIFY=>1 } );
To see the same image, scaled 1:1 with device pixels, say:
$win->imag( $x, { SCALE=>1 } );
To see an image made on a device with 1:2 pixel aspect ratio, with X pixels the same as original image pixels, say
$win->imag( $x, { PIX=>0.5, SCALE=>2 } );
To display an image at 100 dpi on any device, say:
$win->imag( $x, { PITCH=>100 } );
To display an image with 100 micron pixels, say:
$win->imag( $x, { PITCH=>10, UNIT=>'mm' } );
imag1 π§
Display an image with correct aspect ratio
$win->imag1 ( $image, [$min, $max, $transform], [$opt] )
This is syntactic sugar for
$win->imag( { PIX=>1, ALIGN=>'CC' } );
rgbi π
Display an RGB color image
The calling sequence is exactly like imag, except that the input image must have three dimensions: N x M x 3. The last dimension is the (R,G,B) color value. This routine requires pgplot 5.3devel or later. Calling rgbi explicitly is not necessary, as calling image with an appropriately dimensioned RGB triplet makes it fall through to rgbi.
fits_imag β
Display a FITS image with correct axes
$win->fits_imag( image, [$min, $max], [$opt] );
NOTES
Titles: Currently fits_imag also generates titles for you by default and appends the FITS header scientific units if they're present. So if you say
$pdl->hdr->{CTYPE1} = "Flamziness";
$pdl->hdr->{CUNIT1} = "milliBleems";
$win->fits_imag($pdl);
then you get an X title of "Flamziness (milliBleems)". But you can (of course) override that by specifying the XTitle and YTitle switches:
$win->fits_imag($pdl,{Xtitle=>"Arbitrary"});
will give you "Arbitrary" as an X axis title, regardless of what's in the header.
Scaling and aspect ratio: If CUNIT1 and CUNIT2 (or, if they're missing, CTYPE1 and CTYPE2) agree, then the default pixel aspect ratio is 1 (in scientific units, NOT in original pixels). If they don't agree (as for a spectrum) then the default pixel aspect ratio is adjusted automatically to match the plot viewport and other options you've specified.
Okay so you can absolutely override the image scaling with the SCALE, PIX, or PITCH options, same way you would with imag() β BUT bestie, hear me: those parameters refer to the scientific coordinate system, not the pixel coordinate system. So "PITCH=>100" means "100 scientific units per inch", and "SCALE=>1" means "1 scientific unit per device pixel". Go read the imag() writeup for the full tea on these options.
The default value of the "ALIGN" option is 'CC' β centering the image both vertically and horizontally. π
β¨ Axis direction β¨
By default, fits_imag tries to guess which direction your axes are meant to go (left-to-right or right-to-left) using the CDELT keywords: if "CDELT" is negative, then rather than reflecting the image, fits_imag will plot the X axis so that the highest values are on the left.
This is the most convenient behavior for folks who use calibrated (RA,DEC) images, but it is technically incorrect. π To force the direction, use the DirAxis option. Setting "DirAxis=>1" (abbreviated "di=>1") will force the scientific axes to increase to the right, reversing the image as necessary.
π Color wedge π
By default fits_imag draws a color wedge on the right; you can explicitly set the "DrawWedge" option to 0 to avoid this. Use the "WTitle" option to set the wedge title.
πΈ Alternate WCS coordinates πΈ
The default behaviour is to use the primary/default WCS information in the FITS header (i.e. the "CRVAL1","CRPIX1",... keywords). The Greisen et al. standard (http://fits.cv.nrao.edu/documents/wcs/wcs.html) allows alternative/additional mappings to be included in a header; these are denoted by the letters "A" to "Z". If you know that your image contains such a mapping then you can use the "WCS" option to select the appropriate letter. For example, if you had read in a Chandra image created by the CIAO software package then you can display the image in the "physical" coordinate system by saying:
$win->fits_imag( $pdl, { wcs => 'p' } );
The identity transform is used if you select a mapping for which there is no information in the header. Please note that this support is experimental and is not guaranteed to work correctly; please see the documentation for the "_FITS_tr" routine for more information.
πΌοΈ fits_rgbi πΌοΈ
Display an RGB FITS image with correct axes
$win->fits_rgbi( image, [$min,$max], [$opt] );
Works exactly like "fits_imag", but the image must be in (X,Y,RGB) form. Only the first two axes of the FITS header are examined. β¨
π fits_cont π
Draw contours of an image, labelling the axes using the WCS information in the FITS header of the image.
$win->fits_cont( image, [$contours, $transform, $misval], [$opt] )
Does the same thing for the "cont" routine that "fits_imag" does for the "imag" routines. π
π draw_wedge π
Add a wedge (colour bar) to an image.
$win->draw_wedge( [$opt] )
Adds a wedge β shows the mapping between colour and value for a pixel β to the current image. This can also be achieved by setting "DrawWedge" to 1 when calling the "imag" routine.
The colour and font size are the same as used to draw the image axes (although this will probably fail if you did it yourself π). To control the size and location of the wedge, use the "Wedge" option, giving it a hash reference containing any of the following:
Sideβ Which side of the image to draw the wedge: can be one of'B','L','T', or'R'. Default is'R'.Displacementβ How far from the edge of the image should the wedge be drawn, in units of character size. To draw within the image use a negative value. Default is1.5.Widthβ How wide should the wedge be, in units of character size. Default is2.Labelβ A text label to be added to the wedge. If set, it is probably worth increasing the"Width"value by about1to keep the text readable. Default is''. This is equivalent to the"WTitle"option to"imag","fits_imag", and similar methods.ForeGround(synonymFg) β The pixel value corresponding to the"maximum"colour. If"undef", uses the value used by"imag"(recommended choice). Default is"undef".BackGround(synonymBg) β The pixel value corresponding to the"minimum"colour. If"undef", uses the value used by"imag"(recommended choice). Default is"undef".
$x = rvals(50,50);
$win = PDL::Graphics::PGPLOT::Window->new();
$win->imag( $x, { Justify => 1, ITF => 'sqrt' } );
$win->draw_wedge( { Wedge => { Width => 4, Label => 'foo' } } );
# although the following might be more sensible
$win->imag( $x, { Justify => 1, ITF => 'sqrt', DrawWedge => 1,
Wedge => { Width => 4, Label => 'foo'} } );
π¨ ctab π¨
Load an image colour table.
Usage:
ctab ( $name, [$contrast, $brightness] ) # Builtin col table
ctab ( $ctab, [$contrast, $brightness] ) # $ctab is Nx4 array
ctab ( $levels, $red, $green, $blue, [$contrast, $brightness] )
ctab ( '', $contrast, $brightness ) # use last color table
Note: See PDL::Graphics::LUT for access to a large number of colour tables. π
Notionally, all non-RGB images and vectors have their colors looked up in the window's color table. Colors in images and such are scaled to a normalized pseudocolor domain on the line segment [0,1]; the color table is a piecewise linear function that maps this one-dimensional scale to the three-dimensional normalized RGB color space [0,1]^3.
You can specify specific indexed colors by appropriate use of the (levels,red,green,blue) syntax β but that is deprecated, since the actual available number of colors can change depending on the output device. (Someone needs to write a specific hardware-dependent lookup table interface π).
See also "imag" for a description of how to use only part of the color table for a particular image.
π ctab_info π
Return information about the currently loaded color table
π autolog π
Turn on automatic logarithmic scaling in "line" and "points"
Usage: autolog([0|1]);
Setting the argument to 1 turns on automatic log scaling and setting it to zero turns it off again. The function can be used in both the object oriented and standard interface. To learn more, see the documentation for the axis option.
my $win = PDL::Graphics::PGPLOT::Window->new(dev=>'/xserve');
my $x=sequence(10);
my $y=$x*$x+1;
$win->autolog(1);
$win->line($x,$y, {Axis => 'LogY'});
π line π
Plot vector as connected points
If the 'MISSING' option is specified, those points in the $y vector which are equal to the MISSING value are not plotted, but are skipped over. This allows one to quickly draw multiple lines with one call to "line", for example to draw coastlines for maps. πΊοΈ
Usage: line ( [$x,] $y, [$opt] )
The following standard options influence this command:
AXIS, BORDER, COLO(U)R, LINESTYLE, LINEWIDTH, MISSING,
JUSTIFY, SCALE, PITCH, PIX, ALIGN
$x = sequence(10)/10.;
$y = sin($x)**2;
# Draw a red dot-dashed line
line $x, $y, {COLOR => 'RED', LINESTYLE=>3};
γ°οΈ lines γ°οΈ
Plot a list of vectors as discrete sets of connected points
This works much like "line", but for discrete sets of connected points. There are two ways to break lines: you can pass in x/y coordinates just like in "line", but with an additional "pen" ndarray that indicates whether the pen is up or down on the line segment following each point (so you set it to zero at the end of each line segment you want to draw); or you can pass in an array ref containing a list of single polylines to draw.
Happily, there's extra meaning packed into the "pen" ndarray: it multiplies the COLO(U)R that you set, so if you feed in boolean values you get what you expect β but you can also feed in integer or floating-point values to get multicolored lines. π
Furthermore, the sign bit of "pen" can be used to draw hairline segments: if "pen" is negative, then the segment is drawn as though it were positive but with LineWidth and HardLW set to 1 (the minimum).
Equally happily, even if you are using the array ref mechanism to break your polylines you can feed in an array ref of "pen" values to take advantage of the color functionality or further dice your polylines.
Note that, unlike "line", "lines" has no no specify-$y-only calling path. That's because "lines" is intended more for line art than for plotting, so you always have to specify both $x and $y.
Infinite or bad values are ignored β that is to say, if your vector contains a non-finite point, that point breaks the vector just as if you set pen=0 for both that point and the point before it.
Usage: $w->lines( $x, $y, [$pen], [$opt] );
$w->lines( $xy, [$pen], [$opt] );
$w->lines( \@xvects, \@yvects, [\@pen], [$opt] );
$w->lines( \@xyvects, [\@pen], [$opt] );
The following standard options influence this command:
AXIS, BORDER, COLO(U)R, LINESTYLE, LINEWIDTH, MISSING,
JUSTIFY, SCALE, PITCH, PIX, ALIGN
CAVEAT: Setting"pen"elements to0prevents drawing altogether, so you can't use that to draw in the background color. π
β points β
Plot vector as points
Usage: points ( [$x,] $y, [$symbol(s)], [$opt] )
Options recognised:
SYMBOLβ Either an ndarray with the same dimensions as$x, containing the symbol associated to each point or a number specifying the symbol to use for every point, or a name specifying the symbol to use according to the following (recognised name in capital letters):
0 - SQUARE 1 - DOT 2 - PLUS 3 - ASTERISK
4 - CIRCLE 5 - CROSS 7 - TRIANGLE 8 - EARTH
9 - SUN 11 - DIAMOND 12- STAR
PLOTLINEβ If this is>0a line will be drawn through the points.
The following standard options influence this command:
AXIS, BORDER, CHARSIZE, COLOUR, LINESTYLE, LINEWIDTH,
JUSTIFY, SCALE, PIX, PITCH, ALIGN
"SymbolSize" allows adjusting the symbol size, it defaults to CharSize.
The "ColorValues" option allows one to plot XYZ data with the Z axis mapped to a color value. For example:
use PDL::Graphics::LUT;
ctab(lut_data('idl5')); # set up color palette to 'idl5'
points ($x, $y, {ColorValues => $z});
$y = sequence(10)**2+random(10);
# Plot blue stars with a solid line through:
points $y, {PLOTLINE => 1, COLOUR => BLUE, symbol => STAR}; # case insensitive
π¨ errb π¨
Plot error bars (using pgerrb())
Usage:
errb ( $y, $yerrors, [$opt] )
errb ( $x, $y, $yerrors, [$opt] )
errb ( $x, $y, $xerrors, $yerrors, [$opt] )
errb ( $x, $y, $xloerr, $xhierr, $yloerr, $yhierr, [$opt])
Any of the error bar parameters may be "undef" to omit those error bars. π«Ά
okay so the options it knows about:
TERMβ length of terminals, in multiples of the default length πSYMBOLβ plot the datapoints using the symbol value you hand it, either as a name or as a number β go read the docs forpointsfor the deets β¨
and these standard options also influence this command:
AXIS, BORDER, CHARSIZE, COLOUR, LINESTYLE, LINEWIDTH, JUSTIFY, SCALE, PIX, PITCH, ALIGN
$y = sequence(10)**2+random(10);
$sigma=0.5*sqrt($y);
errb $y, $sigma, {COLOUR => RED, SYMBOL => 18};
# plot X bars only
errb( $x, $y, $xerrors, undef );
# plot negative going bars only
errb( $x, $y, $xloerr, undef, $yloerr, undef );
π cont
Display image as contour map. it's giving topographic map but make it β¨aestheticβ¨
Usage:
cont ( $image, [$contours, $transform, $misval], [$opt] )
Notes: $transform for image/cont etc. works exactly the same way as the TR() array in the underlying PGPLOT FORTRAN routine, except fortunately it's zero-offset. You can use the transform() routine to build this ndarray, bestie π
Options it recognises:
CONTOURSβ an ndarray holding the contour levelsFOLLOWβ follow the contour lines all the way around (this makes it usepgcontinstead ofpgcons). If you set this to something>0, the linestyle you picked gets ignored and it'll use a solid line for the positive contours and a dashed line for the negative ones. periodt.LABELSβ an array of strings with a label for each contourLABELCOLOURβ the colour of the labels, if you want it different from the draw colour. This will not mess with the draw colour you set via the colour keyword, promise πMISSINGβ the value to ignore when contouringNCONTOURSβ how many contours you want when it auto-creates them;CONTOURSoverrides thisTRANSFORMβ the pixel-to-world coordinate transform vector
And these standard options influence this command too:
AXIS, BORDER, COLOUR, LINESTYLE, LINEWIDTH, JUSTIFY, SCALE, PIX, PITCH, ALIGN
$x=sequence(10,10);
$ncont = 4;
$labels= ['COLD', 'COLDER', 'FREEZING', 'NORWAY']
# This will give four blue contour lines labelled in red.
cont $x, {NCONT => $ncont, LABELS => $labels, LABELCOLOR => RED,
COLOR => BLUE}
π¦ bin
Plot vector as histogram β like, bin(hist($data)) vibes fr fr
Usage:
bin ( [$x,] $data )
Options it recognises:
CENTREβ (default =1) if it's true, the x values mean the centre of the bin; otherwise they give the lower-edge (in x) of the binCENTERβ same thing asCENTREπ
These standard options influence this command:
AXIS, BORDER, COLOUR, JUSTIFY, LINESTYLE, LINEWIDTH
π
hi2d
Plot image as 2d histogram (not very good IMHOβ¦ π honestly girl, I said what I said)
Usage:
hi2d ( $image, [$x, $ioff, $bias], [$opt] )
Options it recognises:
IOFFSETβ the offset for each array slice.>0slants it to the right,<0to the left.BIASβ the bias to shift each array slice up by.
These standard options influence this command:
AXIS, BORDER, JUSTIFY, SCALE, PIX, PITCH, ALIGN
Heads up bestie: messing withioffsetandbiaswill lowkey often mean you gotta change the default plot range a bit. Also worth knowing β if you've got TriD working, you're probably better off usingmesh3dor some similar command. Go see the PDL::Graphics::TriD module β¨
$r=sequence(100)/50-1.0;
$y=exp(-$r**2)*transpose(exp(-$r**2))
hi2d $y, {IOFF => 1.5, BIAS => 0.07};
π arrow
Plot an arrow.
Usage:
arrow($x1, $y1, $x2, $y2, [, $opt]);
Draws an arrow from $x1, $y1 to $x2, $y2. You can shape the arrow with the option Arrow. Peep the docs for general options for all the details on that option (and the example below π):
Example:
arrow(0, 1, 1, 2, {Arrow => {FS => 1, Angle => 1, Vent => 0.3, Size => 5}});
which draws a broad, large arrow from (0, 1) to (1, 2). slay π
π rect
Draw a non-rotated rectangle.
Usage:
rect ( $x1, $x2, $y1, $y2 )
Options recognised:
These standard options influence this command:
AXIS, BORDER, COLOUR, FILLTYPE, HATCHING, LINESTYLE, LINEWIDTH, JUSTIFY, SCALE, PIX, PITCH, ALIGN
π§ poly
Draw a polygon.
Usage:
poly ( $x, $y )
Options recognised:
These standard options influence this command:
AXIS, BORDER, COLOUR, FILLTYPE, HATCHING, LINESTYLE, LINEWIDTH, JUSTIFY, SCALE, PIX, PITCH, ALIGN
# Fill with hatching in two different colours
$x=sequence(10)/10;
# First fill with cyan hatching
poly $x, $x**2, {COLOR=>5, FILL=>3};
hold;
# Then do it over again with the hatching offset in phase:
poly $x, $x**2, {COLOR=>6, FILL=>3, HATCH=>{PHASE=>0.5}};
release;
β circle
Plot a circle on the display using the fill setting.
Usage:
circle($x, $y, $radius [, $opt]);
All the arguments can alternatively be handed over in the options hash, using these options:
XCenterandYCenterβ the position of the center of the circle πRadiusβ the radius of the circle.
π ellipse
Plot an ellipse, optionally using fill style.
Usage:
ellipse($x, $y, $smaj, $smin, $theta [, $opt]);
All the arguments can alternatively be given in the options hash, using these options (and for historical reasons the names MajorAxis and MinorAxis got kept around even though they really mean the semi-axes, iykyk):
MajorAxisβ the semi-major axis of the ellipse β this has to be defined, or you gotta pass$smaj.MinorAxisβ the semi-minor axis, and likeMajorAxis, this one's required unless you pass$smin.Theta(synonymAngle) β the orientation of the ellipse β defaults to0.0. This is in radians.XCenterandYCenterβ the coordinates of the center of the ellipse. These must be specified, or$xand$ymust be given.NPointsβ the number of points used to draw the ellipse. Defaults to100, and you might need to change it if your ellipse is very large π
This routine also recognises the same standard options that poly accepts.
πΈ rectangle
Draw a rectangle.
Usage:
rectangle($xcenter, $ycenter, $xside, $yside, [, $angle, $opt]);
This routine draws a rectangle with the fill style you chose. Internally it calls poly, which is a lil bit slower than pgrect but which lets you do rotated rectangles too β¨ The routine recognises the same options as poly, plus these extra ones:
XCenterandYCenterβ the position of the center of the rectangle.XCentreandYCentreare valid synonyms πXSideandYSideβ the length of the X and Y sides. If you only specify one of them, the shape is taken to be a square with that as the side-length β or alternatively you can just setSide.Sideβ the length of the sides of the rectangle (so, in this case, a square) β it's syntactic sugar for settingXSideandYSideidentical.XSideorYSideoverride this if either of those are set.Angle(synonymTheta) β the angle at which the rectangle gets drawn. Defaults to0.0and is given in radians.
π vect
Display 2 images as a vector field.
Usage:
vect ( $w, $x, $y, [$scale, $pos, $transform, $misval], { opt } );
$w->vect($x,$y,[$scale,$pos,$transform,$misval], { opt });
Notes: $transform for image/cont etc. is used the same way as the TR() array in the underlying PGPLOT FORTRAN routine but β fortunately β it's zero-offset. You can use the transform() routine to create this ndarray.
This routine plots a vector field. $x is the horizontal component and $y is the vertical component. The scale factor converts between vector length units and scientific positional units. You can set the scale, position, etc. either by passing in parameters in the normal parameter list, or by passing in options π«Ά
Options recognised:
SCALEβ set the scale factor for vector lengths.POSβ set the position of vectors.<0β vector head at coordinate>0β vector base at coordinate=0β vector centered on the coordinate
TRANSFORMβ the pixel-to-world coordinate transform vectorMISSINGβ elements with this value are ignored.
These standard options influence this command:
ARROW, ARROWSIZE, AXIS, BORDER, CHARSIZE, COLOUR, LINESTYLE, LINEWIDTH,
$x=rvals(11,11,{Centre=>[5,5]});
$y=rvals(11,11,{Centre=>[0,0]});
vect $x, $y, {COLOR=>YELLOW, ARROWSIZE=>0.5, LINESTYLE=>dashed};
π¦ fits_vect
Display a pair of 2-D ndarrays as vectors, with FITS header interpretation.
Usage:
fits_vect ($x, $y, [$scale, $pos, $transform, $misval] )
fits_vect is to vect as fits_imag is to imag. π cute lil sibling energy
β¨ transform
Create transform array for contour and image plotting.
$win->transform([$xdim,$ydim], $options);
(For info on coordinate transforms, go try PDL::Transform.) This function creates a transform array in the format the image and contouring routines want. You must call it with the dimensions of your image as arguments, or pass those as an anonymous hash β see the example below π
Angleβ the rotation angle of the transform, in radians. Positive numbers rotate the image clockwise on the screen.ImageDimensionsβ the dimensions of the image the transform is needed for. Pass the dimensions as a reference to an array.Pixincβ the increment in output coordinate per pixel.ImageCenter(orImageCentre) β the centre of the image, as an anonymous array or as a scalar, in scientific coordinates. In that second case the x and y value for the center get set equal to this scalar. This is particularly useful in the common case when the center is (0, 0). (ImageCenteroverridesRefPosif both are specified).RefPos(orReferencePosition) β if you wanna set a pixel other than the image centre to a given value, use this option. Hand it a reference to an array containing 2 two-element array references, like so:
RefPos => [ [ $xpix, $ypix ], [ $xplot, $yplot ] ]
This labels pixel ($xpix,$ypix) as being at position ($xplot,$yplot). For example
RefPos => [ [100,74], [ 0, 0 ] ]
sets the scientific coordinate origin to be at the center of the (100,74) pixel coordinate. The pixel coordinates are pixel-centered, and start counting from 0 (as all good pixel coordinates should π ).
Example:
$im = rvals(100, 100);
$w = PDL::Graphics::PGPLOT::Window->new(Device => '/xs');
$t = $w->transform(dims($im), {ImageCenter => 0, Pixinc => 5});
$w->imag($im, {Transform => $t});
π tline
Broadcasted line plotting.
$win->tline($x, $y, $options);
okay so this is a broadcasted interface to line. π¦ which is giving main character energy when you've got a 2D array and you literally just want to plot every single line in one go, no cap. The routine takes whatever options you hand it and applies them in a "reasonable" way β meaning it loops over the options and wraps back around if there are fewer options than lines. it's giving β¨flexibleβ¨.
Example time, bestie:
$h={Colour => ['Red', '1', 4], Linestyle => ['Solid' ,'Dashed']};
$tx=zeroes(100,5)->xlinvals(-5,5);
$ty = $tx + $tx->yvals;
$win->tline($tx, $ty, $h);
πΈ tpoints πΈ
A broadcasted interface to points. π
Usage:
tpoints($x, $y, $options);
fr fr this is the broadcasted glow-up of points. If you've got a 2D array and you wanna plot every line in one go, this is your girl. Same deal as before: the routine applies any options you give it in a "reasonable" way, looping over the options and wrapping if there are fewer options than lines. π
Example:
$h={Colour => ['Red', '1', 4], Linestyle => ['Solid' ,'Dashed']};
$tx=zeroes(100,5)->xlinvals(-5,5);
$ty = $tx + $tx->yvals;
tpoints($tx, $ty, $h);
π tcircle π
A broadcasted interface to circle. π¦
Usage:
tcircle($x, $y, $r, $options);
Broadcasted circle, yes bestie. π This one slays when you've got a whole list of circle centers and radii and you want to draw every single circle in one go. It applies any options you apply in a "reasonable" way, in the sense that it loops over the options and wraps over if there are fewer options than circles. periodt.
Example:
$x=sequence(5);
$y=random(5);
$r=sequence(5)/10 + 0.1;
$h={justify => 1,Color => ['red','green','blue'], filltype => ['solid','outline','hatched','cross_hatched']};
tcircle($x, $y, $r, $h);
heads up bestie β οΈ note that$xand$ymust be the same size (>1D is OK, though meaningless as far astcircleis concerned).$rcan be the same size as$xOR a 1-element ndarray OR a single perl scalar. π
π Text routines π
π text π
Write text in a plot window at a specified position. β¨
Usage:
text ($text, $x, $y [, $opt])
Options recognised:
"ANGLE"β the angle in degrees between the baseline of the text and the horisontal (increasing counter-clockwise). This defaults to0. π"JUSTIFICATION"β the justification of the text relative to the position specified. It defaults to0.0, which gives left-justified text. A value of0.5gives centered text and a value of1.0gives right-justified text. π«Ά"XPos","YPos","Text"β these give alternative ways to specify the text and position. π"BackgroundColour"β this sets the background colour for the text in case an opaque background is desired. You can also use the synonyms"Bg"and"BackgroundColor". π
The following standard options influence this command:
COLOUR, CHARSIZE
line sequence(10), sequence(10)**2;
text 'A parabola', 3, 9, {Justification => 1, Angle=>atan2(6,1)};
β legend β
Add a legend to a plot. π¦
Usage:
legend($text, $x, $y, [, $width], $opt]);
This function adds a legend to an existing plot. The action is primarily controlled by the info in the options hash, and the basic idea is that $x and $y determine the upper left hand corner of the box in which the legend goes. If the width is specified either as an argument or as an option in the option hash, this is used to determine the optimal character size to fit the text into part of this width (defaults to 0.5 β see the description of "TextFraction" below π). The rest of the width gets filled out with either lines or symbols according to the content of the "LineStyle", "Symbol", "Colour" and "LineWidth" options. iykyk π
The local options recognised are as follows:
"Text"β an anonymous array of annotations, can also be specified directly. π"XPos"and"YPos"β the X and Y position of the upper left-hand corner of the text. π"Width"and"Height"β the width and/or height of each line (including symbol/line). This is used to determine the character size. If any of these are set to'Automatic'the current character size will be used. π"TextFraction"β the text and the symbol/line is set inside a box."TextFraction"determines how much of this box should be devoted to text. This defaults to0.5. You can also use"Fraction"as a synonym to this. π"TextShift"β this option allows for fine control of the spacing between the text and the start of the line/symbol. It is given in fractions of the total width of the legend box. The default value is0.1. β¨"VertSpace"or"VSpace"β by default the text lines are separated by one character height (in the sense that if the separation were0then they would lie on top of each other π). The"VertSpace"option allows you to increase (or decrease) this gap in units of the character height; a value of0.5would add half a character height to the gap between lines, and-0.5would remove the same distance. The default value is0. π"BackgroundColour"β this sets the background colour for the text in case an opaque background is desired. You can also use the synonyms"Bg"and"BackgroundColor". π
line $x, $y, {Color => 'Red', LineStyle => 'Solid'};
line $x2, $y2, {Color => 'Blue', 'LineStyle' => 'Dashed', LineWidth => 10};
legend ['A red line', 'A blue line'], 5, 5,
{LineStyle => ['Solid', 'Dashed'], Colour => ['Red', 'Blue']
LineWidth => [undef, 10]}; # undef gives default.
π§ Cursor routines π§
π cursor π
Interactively read cursor positions. π±οΈ
Usage:
($x, $y, $ch, $xref, $yref) = cursor($opt)
This routine has no standard input parameters, but the type of cursor can be set by setting the option "Type" as a key in the anonymous hash $opt. The first three return values from the function are always defined and give the position selected by the user and the character pressed. β¨οΈ
Depending on the cursor type selected, the last two arguments might also be defined and these give a reference position. For instance if the cursor is selected to be "Rectangle" then the reference position gives one of the corners of the rectangle and $x and $y the diagonally opposite one. π
Options recognised:
XRef,YRefβ the reference position to be used. πTypeβ the type of cursor. This can be selected using a number between0and7as in PGPLOT, or alternatively you can specify these as"Default"(0),"RadialLine"(1),"Rectangle"(2),"TwoHorizontalLines"(3),"TwoVerticalLines"(4),"HorizontalLine"(5),"VerticalLine"(6) and"CrossHair"(7) respectively. The default cursor is just the normal mouse cursor. π±οΈ
For the "RadialLine" you must specify the reference point, whereas for the "Two(Vertical|Horizontal)Lines" cursor the X or Y reference point, respectively, must be specified. no skipping this bestie π
To select a region on a plot, use the rectangle cursor:
($x, $y, $ch, $xref, $yref) = cursor({Type => 'Rectangle'});
poly pdl($x, $xref, $xref, $x, $x), pdl($y, $y, $yref, $yref, $y);
To select a region of the X-axis:
($x1, $y1, $ch) = cursor({Type => 'VerticalLine'});
($x2, $y2, $ch) = cursor({Type => 'TwoVerticalLines', XRef => $x1});
π Internal routines π
okay bestie, this is the backstage area. the lights are still on, but you're not supposed to be wandering around back here unless you know what you're doing. i'm telling you anyway because you're my girl.
π«Ά catch_signals π«Ά
so to prevent pgplot from doing a fandango on core, we have to block interrupts during PGPLOT calls. specifically, INT needs to get caught. these internal routines provide a mechanism for that.
you simply bracket any PGPLOT calls with catch_signals:
catch_signals {
...
pgcube($n, $x->get_dataref);
};
and the signal_catcher will queue up any signals (like INT -- the control-C interrupt) until the end of the block. so if you smash ctrl-C mid-plot, it waits its turn instead of wrecking the whole vibe π
π¦ _open_new_window π¦
Open a new window. This sets the window ID, which is the one used when accessing a window later using pgslct. It also sets the window name to something easily remembered if it has not been set before.
πΈ _setup_window πΈ
This routine sets up a new window with its shape and size. This is also where the size options are actually parsed. These are then forgotten (well, they are stored in $self->{Options}) and the corresponding aspect ratio and window width is stored. See the discussion under new() for the logic.
Finally the subpanels are set up using pgsubp and colours and linewidth are adjusted according to whether we have a hardcopy device or not.
π _status π
This routine checks PGPLOT's status for the window. It returns OPEN if the window is open and CLOSED if it is closed. (Windows can be closed but still exist). it's giving ghosting but make it graphics π«
π _reopen π
This functions reopens a window. Since this is an internal function it does not have a lot of error-checking. Make sure the device is closed before calling this routine.
There is an unfortunate problem which pops up viz. that the window name cannot be changed at this point since we are offering that to the rest of the world. That might be sensible, but it means that the window name will not reflect the id of the window - use id() for that (this is also why we do not call open_new_window )
β¨ _advance_panel β¨
This routine advances one plot panel, updating the CurrentPanel as well. If the advance will proceed past the page the page will be erased. Also note that when you advance one panel the hold value will be changed.
π _check_move_or_erase π
This routine is a utility routine which checks if we need to move panel, and if so will do this. It also checks if it is necessary to advance panels, and whether they need to be erased.
π
_broadcast_options π
This function is a cludgy utility function that expands an options hash to an array of hashes looping over options. This is mainly of use for "broadcasted" interfaces to standard plotting routines. cludgy! the author said it, not me π
π options π
Access the options used when originally opening the window. At the moment this is not updated when the window is changed later.
β id β
Access the window ID that PGPLOT uses for the present window.
π§ device π§
This function returns the device type of the present window.
πΈ name πΈ
Accessor to set and examine the name of a window.
π focus π
Set focus for subsequent PGPLOT commands to this window. main character energy, but for a window β¨
π₯ info π₯
Get general information about the PGPLOT environment.
@ans = $self->info( @item );
The valid values of @item are as below, where case is not important:
VERSIONβ What PGPLOT version is in use.STATEβ The status of the output device, this is returns'OPEN'if the device is open and'CLOSED'otherwise.USERβ The username of the owner of the spawning program.NOWβ The current date and time in the format'dd-MMM-yyyy hh:mm'. Most people are likely to use Perl functions instead.DEVICE* β The current PGPLOT device or file, see alsodevice().FILE* β The filename for the current device.TYPE* β And the device type for the current device.DEV/TYPE* β This combinesDEVICEandTYPEin a form that can be used as input tonew.HARDCOPY* β This is flag which is set to'YES'if the current device is a hardcopy device and'NO'otherwise.TERMINAL* β This flag is set to'YES'if the current device is the user's terminal and'NO'otherwise.CURSOR* β A flag ('YES'or'NO') to inform whether the current device has a cursor.
Those items marced with a "*" only return a valid answer if the window is open. A question mark ("?") is returned if the item is not recognised or the information is not available.
π¦ _extract_hash π¦
This routine takes and array and returns the first hash reference found as well as those elements that are not hashes. Note the latter point because all other references to hashes in the array will be lost. gone. poof. bestie be careful π
π _parse_unit π
Convert a unit string or number into a PGPLOT-certified length unit specification, or return undef if it won't go.
π _parse_options π
This is a convenience routine for parsing a set of options. It returns both the full set of options and those that the user has set.
π _save_status π
Saves the PGPLOT state so that changes to settings can be made and then the present state restored by _restore_status.
π _restore_status π
Restore the PGPLOT state. See _save_status.
β _checkarg β
This routine checks and optionally alters the arguments given to it.
π
_set_colour π
This is an internal routine that encapsulates all the nastiness of setting colours depending on the different PGPLOT colour models (although HLS is not supported).
The routine works in the following way:
- At initialisation of the plot device the work colour index is set to 16. The work index is the index the routine will modify unless the user has specified something else.
- The routine should be used after standard interpretation and synonym matching has been used. So if the colour is given as input is an integer that colour index is used.
- If the colour is a reference the routine checks whether it is an
"ARRAY"or a"PDL"reference. If it is not an error message is given. If it is a"PDL"reference it will be converted to an array ref. - If the array has four elements the first element is interpreted as the colour index to modify and this overrules the setting for the work index used internally. Otherwise the work index is used and incremented until the maximum number of colours for the output device is reached (as indicated by
"pgqcol"). Should you wish to change that you need to read the PGPLOT documentation - it is somewhat device dependent. - When the array has been recognised the R,G and B colours of the user-set index or work index is set using the
"pgscr"command and we are finished. - If the input colour instead is a string we try to set the colour using the PGPLOT routine
"pgscrn"with no other error-checking. This should be ok, as that routine returns a rather sensible error-message.
π§ _standard_options_parser π§
This internal routine is the default routine for parsing options. This routine deals with a subset of options that most routines will accept.
π _image_xyrange π
Given a PGPLOT tr matrix and an image size, calculate the data world coordinates over which the image ranges. This is used in "imag" and "cont". It keeps track of the required half-pixel offset to display images properly -- eg feeding in no tr matrix at all, nx=20, and ny=20 will will return (-0.5,19.5,-0.5,19.5). It also checks the options hash for XRange/YRange specifications and, if they are present, it overrides the appropriate output with the exact ranges in those fields.
π _FITS_tr π
Given a FITS image, return the PGPLOT transformation matrix to convert pixel coordinates to scientific coordinates. Used by "fits_imag", "fits_rgbi", and "fits_cont", but may come in handy for other methods.
my $tr = _FITS_tr( $win, $img );
my $tr = _FITS_tr( $win, $img, $opts );
The return value ($tr in the examples above) is the same as returned by the transform() routine, with values set up to convert the pixel to scientific coordinate values for the two-dimensional image $img. The $opts argument is optional and should be a HASH reference; currently it only understands one key (any others are ignored):
WCS => undef (default), "", or "A" to "Z"
Both the key name and value are case insensitive. If left as "undef" or "" then the primary coordinate mapping from the header is used, otherwise use the additional WCS mapping given by the appropriate letter. We make no checks that the given mapping is available; the routine falls back to the unit mapping if the specified system is not available.
The WCS option has only been tested on images from the Chandra X-ray satellite (<http://chandra.harvard.edu/>) created by the CIAO software package (<http://cxc.harvard.edu/ciao/>), for which you should set "WCS => "P"" to use the "PHYSICAL" coordinate system.
See <http://fits.cv.nrao.edu/documents/wcs/wcs.html> for further information on the Representation of World Coordinate Systems in FITS.
π§ INTERNAL π§
The coding tries to follow reasonable standards, so that all functions starting with an underscore should be considered as internal and should not be called from outside the package. In addition most routines have a set of options. These are encapsulated and are not accessible outside the routine. This is to avoid collisions between different variables.
fr fr: leading underscore = do not touch. iykyk π
π AUTHOR π
Karl Glazebrook [kgb@aaoepp.aao.gov.au] modified by Jarle Brinchmann (jarle@astro.ox.ac.uk) who is also responsible for the OO interface, docs mangled by Tuomas J. Lukka (lukka@fas.harvard.edu) and Christian Soeller (c.soeller@auckland.ac.nz). Further contributions and bugfixes from Kaj Wiik, Doug Burke, Craig DeForest, and many others.
All rights reserved. There is no warranty. You are allowed to redistribute this software / documentation under certain conditions. For details, see the file COPYING in the PDL distribution. If this file is separated from the PDL distribution, the copyright notice should be included in the file.
no warranty, bestie. it's giving "as-is, good luck, ily" ππ«Ά
and that's a wrap on the whole page!! πβ¨ this one came to you from perl v5.38.2, dated 2024-04-10, and it's the Window(3pm) page π go make something pretty, you've got this ππ¦
π¦ where this page comes from
- ubuntu noble: pdl 1:2.085-1ubuntu1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms