Plot/Full-Text

From J Wiki
Jump to navigation Jump to search
Plot | Verbs | Class Commands Data Options Outputs Types | Colors Fonts Keys Text YAxes | Function Multi Shape
Plot.png

Plot is a plotting package that provides business and scientific graphics.

Quick Start  - Information for users

  • For an introduction, load J and run lab Plot Package
  • For examples, see Examples
  • An HTML snapshot of the Plot section is available for offline browsing as part of the wikihtml addon.
  • Contrib - user examples and solutions

Explore  - user documentation, see also the top navigation bar.

  • Class - describes the plot class, for example, to include plots on a form
  • Colors - colors used in a plot
  • Commands - plot commands
  • Data - plot data
  • Fonts - supported fonts
  • Function Plots - plotting functions, instead of data
  • Keys - defining keys
  • Multiplots - multiple plots in a single plot window
  • Options - lists plot options
  • Outputs - lists the available outputs
  • Shape - definition of plot sub windows
  • Text - including text on a plot
  • Types - lists the available plot types
  • Verbs - describes the two main verbs, pd (plot driver) and plot
  • Y-Axes - defining separate left and right y-axes

Development  - Information for developers

  • Layout - explanation of plot layout calculations
  • Source - source for plot


Note: The jhs or j playground environments display multiple invocations of the plot verb in a persistent fashion (inline in the "terminal session") while jqt displays multiple invocations of the plot verb by updating the plot window.


Contributed by Chris Burke.

Class

Plot | Verbs | Class Commands Data Options Outputs Types | Colors Fonts Keys Text YAxes | Function Multi Shape

Plot is defined in class jzplot.

Public verbs are pd and plot.

Public nouns that specify the Windows form and isigraph control id:

Name Description Default
PForm form id plot
PFormhwnd form handle defined when the form is created
PId isigraph control id gs

Example: create two plots

The following draws two independent plots:

load 'jzplot'          NB. load plot class
a=: conew 'jzplot'     NB. create plot object a
b=: conew 'jzplot'     NB. create plot object b
plot__a */~ i:15       NB. draw plot in a
plot__b +./~ i:15      NB. draw plot in b

Example: add plot to a form

Prior to J8.02, you needed to define the public nouns PForm, PFormhwnd and PId. These override the default values.

require 'gtkwd jzplot' NB. load plot class (gtkwd only required by J7)

MYPLOT=: 0 : 0
pc myplot;
xywh 0 0 225 200;cc g0 isigraph ws_border rightscale bottommove;
xywh 231 3 40 12;cc close button leftmove rightmove;cn "Close";
pas 2 0;pcenter;
rem form end;
)

myplot_run=: 3 : 0
wd MYPLOT
loc=: conew 'jzplot'             NB. create plot object
PForm__loc=: 'myplot'            NB. define PForm in loc
PFormhwnd__loc=: wd 'qhwndp'     NB. define PFormhwnd in loc
PId__loc=: 'g0'                  NB. define PId in loc
'density' plot__loc 7|i.25 25    NB. draw plot on the form
wd 'pshow'
)

myplot_g0_paint=: 3 : 0
pd__loc 'show'                   NB. call show in paint handler
)

myplot_cancel=: myplot_close_button=: 3 : 0
destroy__loc''
wd 'pclose'
)

myplot_run''

In J8.02 plotting to an isigraph control has been somewhat simplified. The code below should be functionally equivalent to the example above.

require 'jzplot'

MYPLOT=: 0 : 0
pc myplot;
minwh 225 200;
cc g0 isigraph flush;
cc close button;cn "Close";
pas 0 0;
)

myplot_run=: 3 : 0
wd MYPLOT
loc=: ('myplot';'g0') conew 'jzplot'  NB. create plot object
'density' plot__loc 7|i.25 25         NB. draw plot on the form
wd 'pshow'
)

myplot_close=: myplot_close_button=: 3 : 0
wd 'pclose'
destroy__loc''
)

myplot_run''

Example: update a plot in a form

Continuing the previous (pre J8.02) example, suppose you need to update the plot, perhaps in response to a user interaction. You redraw the plot and then use glpaint '' to make the new plot visible:

myplot_g0_update =: 3 : 0
'density' plot__loc 5|i.25 25    NB. draw updated plot on the form
myplot_g0_paint ''               NB. call paint routine to draw pixels
glpaint_jgl2_ ''                 NB. copy updated pixels to the screen
)

The following extends the J8.02 example above, showing how to update the plot based on user interaction

require 'jzplot'

MYPLOT=: 0 : 0
pc myplot;
minwh 225 200;
cc g0 isigraph flush;
cc update button;cn "Update";
cc close button;cn "Close";
pas 0 0;
)

myplot_run=: 3 : 0
wd MYPLOT
Base0=: 7
loc=: ('myplot';'g0') conew 'jzplot'  NB. create plot object
'density' plot__loc Base0|i.25 25     NB. draw plot on the form
wd 'pshow'
)

myplot_close=: myplot_close_button=: 3 : 0
wd 'pclose'
destroy__loc''
)

myplot_update_button =: 3 : 0
Base0=: 3 + 9|Base0-1
'density' plot__loc Base0|i.25 25  NB. draw updated plot on the form
glpaint__loc ''                    NB. copy updated pixels to the screen
)

myplot_run''

Colors

Plot | Verbs | Class Commands Data Options Outputs Types | Colors Fonts Keys Text YAxes | Function Multi Shape

Several color schemes are used in Plot.

Before any drawing is made, the backcolor is applied to the plot box. The axes, frame, ticmarks, labels and titles are then drawn in the forecolor.

Text specified with the text , textc and textr commands is drawn with the textcolor.

Data is colored in two ways, depending on plot type:

  • where each data item is plotted in a single color (e.g. line plots), the items are drawn with the itemcolor
  • where a data item is banded and requires several colors to plot, (e.g. density plots), it is drawn with the bandcolor.

The edges of filled-in shapes are drawn with the edgecolor (usually black).

Backcolor, forecolor, textcolor and edgecolor are single colors.

Itemcolor and bandcolor are lists of colors. Itemcolor typically contains quite distinctive colors to distinguish the different data items. Bandcolor is typically a graduated scale of colors, for example to indicate height. Typical lists of colors are defined in ~system\classes\plot\plotdefs.ijs (J-602) or in ~\addons\graphics\plot\plotdefs.ijs (J-801).

The term color can also be used as an abbreviation to specify the itemcolor or the bandcolor depending on plot type. This is convenient for simple plots where only one plot type is being drawn.

The keycolor is used for keys. By default this is the colors used in the plot, however, in some cases you need to specify this separately.

For example:

pd 'itemcolor blue,red,green'     NB. list of colors for items
pd 'bandcolor bgclr'              NB. list of colors in color band
pd 'color blue,red'               NB. item or band colors (depends on plot type)

The jzplot.ijs script defines several color schemes, for example:

  • STDCLR is the color scheme used by default
  • RBCLR , RGCLR , RGBCLR and BGCLR are color schemes that are appropriate for 3D surface plots. Here RBCLR is a scale of 64 steps from red to blue, etc.
  • GRAYSCALE is gray shades in 100 steps from black to white.

The colors in the standard color scheme are given in [1]

Custom color schemes can be defined. The name of the noun containing the list of colors must be all uppercase. So for example a color scheme of 3 colors (red, green and blue) could be defined as:

MYCLR_z_=: 255 0 0 , 0 255 0 ,: 0 0 255

And specified during plotting like this:

pd 'itemcolor MYCLR'

Commands

Plot | Verbs | Class Commands Data Options Outputs Types | Colors Fonts Keys Text YAxes | Function Multi Shape


Summary

reset reset plot
sub,endsub create sub window. All plots are drawn in sub windows. If there is no sub command, the sub window is taken to be the full plot area.
new,multi start plot definition. new starts a single plot, multi starts a multiplot.
use set the current plotting area.
rule,text,textc,textr draw rule and text
show,isi,eps,pdf,pdfr,canvas,canvasr,cairo,cairor create and output plot
save,get,clip,print copy plot to file, data stream, clipboard, printer

Drawing Commands

reset [parent] reset plot with optional parent window id.

For example:

pd 'reset'

sub shape, endsub. Command sub starts a sub plot with given shape, sets plot defaults. Used for creating one or more plot windows. If sub is not used, the plot window is the available area.

The command is recursive - each call to sub starts a new sub plot in the existing window. Use command endsub to end a sub plot and return to the previous window.

For an isigraph plot, the default window is the full area of the isigraph control, which itself defaults to 480 x 360 pixels. For EPS and PDF plots, the default window depends on whether there is an active isigraph window displaying the current plot. If so, the window size is the same as the isigraph window, otherwise it is 0 0 480 360.

For example, create a new sub plot window with xy position 100 100, and of size 400 by 600:

pd 'sub 100 100 400 600'

multi shape starts a multiplot with the given shape. See Multi plots.

new [window] starts a new plot with an optional window definition, sets plot defaults. Use to set initial values, and when displaying multiple plots within the current sub window.

use window change window, leaving option settings unchanged. This does not restore plot defaults.

To draw several plots using the same options to a single sub window, start with pd 'new' for the first plot, and then pd 'use' for the subsequent plots.

[options] sets plot options. See plot Options.

For example:

pd 'backcolor white; frame 1'

[data] sets plot data. See plot Data.

For example:

pd */~i:20

rule arg draw line.

text, textc, textr arg text left aligned, centered, right aligned.

Argument is x y text, where x y are coordinates relative to the current window.

For example, the following writes the text "J Graphics" centered at position 500 950:

pd 'textc 500 950 J Graphics'

See also Text commands.

Output commands

show [opts] display plot using the default output.

Output is isigraph in Jwdw or Jwdp, or GTK in JGTK, or canvas in JHS, or qt in QTIDE, otherwise PDF or cairo.

eps [file w h] (J6 only) display plot in EPS format.

The file defaults to ~temp/plot.eps. The [w h] is the EPS bounding box size, and defaults to the active plot window size in pixels, or 480 360 if none.

gtk (J7 only) display plot in a GTK window, where supported, requires GTK addon.

isi [w h] (J6 only) display plot in an isigraph window.

The [w h] are the pixels, and default to 480 360.

pdf [file w h] display plot in PDF format.

The file defaults to ~temp/plot.pdf. The [w h] is the PDF bounding box size, and defaults to the active plot window size in pixels, or 480 360 if none.

pdfr [w h] return plot as PDF stream.

The [w h] are the same as for pdf.

canvas [file w h context] (J7 or later) display plot in HTML5 canvas element format.

The file defaults to ~temp/plot.html. The [w h] is the canvas bounding box size, and defaults to the active plot window size in pixels, or 400 200 if none. The [context] is a name for identifying the canvas element, only 2 javascript function will be returned if this option is set.

canvasr [w h context] (J7 or later) return plot as HTML5 canvas element stream.

The [w h context] are the same as for canvas.

cairo [file w h] (J7 only) return plot in png format.

The file defaults to ~temp/plot.png. The [w h] is the image bounding box size, and defaults to the active plot window size in pixels, or 400 200 if none.

cairor [w h] (J7 only) return plot as png stream.

The [w h] are the same as for cairo.

qt [w h] (J8 only) display plot in a QT window, where supported, requires QT addon.

The [w h] are the pixels, and default to 480 360.

qtc [file w h] (J803 or later) return plot in image format, requires QT addon. This also works under jconsole (Linux requires X-Window).

The file defaults to ~temp/plot.png. The [w h] are the pixels, and default to 480 360.

See also Outputs.

Copy commands

The following commands copy an isigraph window, and require that an isigraph plot has already been created. To execute one of the copy commands silently, without first displaying the isigraph window, set the Plot option visible to 0. Note that generating an isigraph window uses the gl2 commands that are built into Jwd but not Jconsole. For this reason, it is not currently possible to use the copy commands from a Jconsole session.

clip copy isigraph plot to clipboard.

print print isigraph plot.

save type [options] save isigraph plot to file.

The save command supports several image types/formats. For J6, those marked with an asterisk(*) require that the platimg addon be installed. In each case, a file name is optional. If not given, the file is ~temp/plot.ext, where ext is the file type. For example, the default bmp file is ~temp/plot.bmp.

  • save bmp [file] [w h] save isigraph plot as a bitmap file. The [w h] is the bitmap size, and defaults to the current displayed plot size.
  • save emf [file] save isigraph plot to file in emf format.
  • save jpg [file|quality]* save isigraph plot to file in jpeg format. The quality is a percentage, and defaults to 100 (highest quality).
  • save png [file|compression]* save isigraph plot to file in png format. The compression is a number from 0 to 9, and defaults to 9 (highest compression).
  • save gif [file]* save isigraph plot to file in gif format.
  • save tif [file]* save isigraph plot to file in tif format.

get type return isigraph plot as data stream.

The get command supports several image types/formats. For J6, those marked with an asterisk(*) require that the platimg addon be installed.

  • get jpg* return isigraph plot as a data stream in jpeg format.
  • get png* return isigraph plot as data stream in png format.
  • get gif* return isigraph plot as data stream in gif format.
  • get tif* return isigraph plot as data stream in tif format.

Data

Plot | Verbs | Class Commands Data Options Outputs Types | Colors Fonts Keys Text YAxes | Function Multi Shape

Plot data may be given to the full-action plot command, or to the component sub-command pd, as either a numeric or a boxed array.

A numeric unboxed array should be a vector or matrix.

  • For a plot requiring 2D data, a vector is the y values and a matrix is treated as rows of y values. The x axis defaults to i.{:$y
  • For a plot requiring 3D data, the array should be a matrix and is treated as z values. The x axis defaults to i.# z and the y axis to i.{:$z
  • Complex data is treated as x (real) and y (imaginary) values.

A boxed array is a list of either x;y, or r;theta, or x;y;z lists. The boxed values should conform to each other in size.

  • For a plot requiring 2D data, the x values should have the same shape as the y values, or be a vector of length {:$y
  • For a polar plot (2D only), data is r;theta, a 2-item list of boxed real-valued numerical lists. (Complex-valued data in polar format must first be separated into r-theta lists, which plot will then convert to x-y values.)
  • For a plot requiring 3D data, the x and y values should have the same shape as the z values, or the x values should have length #z and the y values length {:$z

More than one set of data can be given.

Examples

Plot | Verbs | Class Commands Data Options Outputs Types | Colors Fonts Keys Text YAxes | Function Multi Shape

In the J session, see the QT demo Help|Studio|Showcase...|plot. In the demo, use Options|View Definition to view and experiment with the plot definitions.

As from scripts 6.02.041, these demos can be run interactively, in particular this is useful in Jconsole. Try:

J6

load '~system/examples/graphics/plot/plotdemos.ijs'
plotdemos 4     NB. argument is demo number in range 0-54

J7 GTK requires installation of the package demos/plot via Pacman

load '~Demos/plot/plotdemos.ijs'
plotdemos 4     NB. argument is demo number in range 0-54

J7 or J8 with gtkwd, Qt or droidwd should install the package demos/wdplot via Pacman

load '~Demos/wdplot/plotdemos.ijs'
plotdemos 4     NB. argument is demo number in range 0-54

Some examples in the wiki:

Extensibility

The Plot package allows to customize plot parameters to get visual variations, create new graphical solutions from existing or define totally new plot types.

New Solutions from Existing Plot Types

Bubble.png

Visual possibilities of existing plot types are not limited to what can be seen in the plot demo. Sometimes a little creativity can easily exceed the original intentions of certain plot types.

A categorical table from a question in the Forum, Looking for graphical inspiration from Bill Harris, can be represented as a Bubble chart. Although there is no such separate plot type, the effect can be achieved by using the point type and varying the pensize option.

Here we use labels to identify groups, relative positions of the items show their relationship, size represents the level of the relationship, and there is still room for additional detail, such as color to show some additional properties, etc.

Such layout satisfies one of most important principles of Visualization: using little space to convey as many parameters of the model as possible in economical ways without clutter.

label=: [:}:@;('"',,&'" ')each          NB. this fragment can be pasted
diam=:  ('pensize ' <@, ":)"0           NB. to the View Definition window
coord=: $ <@([: ;&,/ 1 + |.@#:)"_ 0 ]   NB. in the Plot Demo
index=: i.@(_1 1&*)@$
view=:  diam ,"0 coord@index
norm=: <.@(* (% >./@,)@(- <./@,))

data=. 10 (0 0;_1 0;_1 _1) } i.4 4    NB. vary indep. 2 2..6 6

colors=. (<'blue') (0 0;_1 0;_1 _1) } ($data)$<'green'
colors=. }:;,&','each  colors

pd 'type point'
pd 'graphbackcolor lightgray'
pd 'gridcolor 230 230 230'
pd 'axes 1 1;axiscolor white'
pd 'xticpos ',":i.2+{:$data
pd 'yticpos ',":i.2+#data
pd 'xlabel ', label (2+{:$data)$<;._1'//L L/H L/L H/H H/'
pd 'ylabel ', label (2+#data)$<;._1'//L L/H L/L H/H H/'
pd 'color ',colors

pd@> view 5+35 norm data

Thanks to Brian Schott for noticing some inconsistencies and helping to improve this example.

-- Oleg Kobchenko <<DateTime(2007-04-06T14:06:04Z)>>

Multi-Pyramid

Multi-pyramid is a way to visualize multi-dimensional arrays with number of axes from 3 to a few more and limited axes lengths.

The structure of the plot is repeated 2D histogram/bar plot made of pyramids. Pyramids make it easy to see through the rows and stacks of such planes. Color can be used to help line up rows or columns.

Multi-Pyramid.png

-- Oleg Kobchenko <<DateTime(2008-07-16T06:44:48Z)>>

Other Customizations

...

Fonts

Plot | Verbs | Class Commands Data Options Outputs Types | Colors Fonts Keys Text YAxes | Function Multi Shape

Plot supports PostScript Type 1 fonts and their Windows equivalents.

Fonts for isigraph drawing may be given in the standard fontspec format, see fontspec.

In addition, fonts may be given as one of the standard PostScript Type 1 fonts. This is a font name and size from the following 14 fonts, arranged in four families:

  • Helvetica, Helvetica-Bold, Helvetica-Oblique, Helvetica-BoldOblique
  • Courier, Courier-Bold, Courier-Oblique, Courier-BoldOblique
  • Times-Roman, Times-Bold, Times-Italic, Times-BoldItalic
  • Symbol, ZapfDingbats

In each case, capitalization is ignored.

The following are equivalent:

pd 'titlefont arial 15 bold italic'
pd 'titlefont helvetica-boldoblique 15'

When drawing to an isigraph window, fonts in either format are accepted.

When drawing to EPS or PDF, fonts are converted if necessary to the PostScript standard. Specifically, Arial maps to Helvetica, Lucida Console to Courier, and Times New Roman to Times-Roman. The default map is to Helvetica.

Other Fonts

Fonts other than the PostScript Type 1 fonts or their Windows equivalents are supported if their font metrics and other required information are available. In the J601 release, this includes two Chinese fonts, MSung-Light (traditional) and STSong-Light (simplified), and these work in isigraph, and output to PDF.

Font Scaling

There is one major difference in the treatment of fonts for output to isigraph, and for other outputs:

  • Font metrics for an isigraph are obtained by using glexent, and represent text size in pixels.
  • Font metrics for other outputs are calculated from font metric tables, and represent text size in points (1/72 inch).

Unfortunately, these two calculations are not the same. Typically, screen resolution is around 96 pixels per inch, so to match a font drawn in an isigraph window, the font needs to be scaled down to 72%96 = 0.75 size when drawn to EPS or PDF.

To enable EPS and PDF plots to match isigraphs, font sizes for these plots are scaled by a factor of FONTSCALE, which is set to 0.75 by default. In this case, plots drawn to isigraph, and to EPS or PDF, appear essentially the same.

This also means that if you specify a font size of say 12 points, then in the EPS or PDF file, the font is actually entered as being 12 * 0.75 = 9 points. To avoid this behaviour, reset plotscale, i.e. use:

pd 'plotscale 1'

Function

Plot | Verbs | Class Commands Data Options Outputs Types | Colors Fonts Keys Text YAxes | Function Multi Shape

Function Plots

The simplest way to plot a function is to give Plot the description of the function and the domain, and let Plot decide where to evaluate the function. You do this by giving the function instead of the data as the last variable in the right argument to plot or pd. The plot may be a 2-D plot or a 3-D plot. An example is

plot 0 10 ; 'sin'

The character string instead of data tells Plot to evaluate the sin function over the interval [0,10]. One advantage of a function plot, besides its simplicity, is that it has the X-axis information so can label that axis correctly. Compare the above example to the equivalent numeric "plot sin 5+i:5j99". In this case, "plot" does not have the X values available so it labels that axis with integers from 0 to 99 as seen here, whereas the function plot labels the X-axis with values 0-10, as given to the function.

FunctionPlotSine0-10.png NumericPlotSine0-10.png

The independent variable(s) are given either as intervals or as lists of points. An interval is indicated by 2 or 3 numbers, specifying start value,end value,number of steps. A list of points is indicated by a boxed argument containing the points, or by an unboxed list of more than 3 points. Multiple intervals or point-lists are allowed.

If the number of steps is omitted or 0, Plot will pick an appropriate number of points to use. It does so by repeatedly subdividing the interval until the curve is smooth or it decides that the curve is discontinous, in which case it plots continuous sections separately.

The subdivision is controlled by the plot options Cfuncres and singtoler. Cfuncres (C is x or y) gives the subdivision resolution: an interval smaller than 1/Cfuncres of the screen will not be split. Cfuncres defaults to twice the pixel resolution of the plot. singtoler is used when the display has singularities, and controls how much of the heading-off-to-infinity tail of the curve will be shown at the singularity. You can experiment to find a good value for singtoler for your application; the default is 10 and higher numbers cause more of the tail to be displayed.

The function(s) to be displayed can be given as a list of gerunds, one for each verb to be drawn, or as a string where the verb-specifiers are separated by the ` character (use doubled ` as an escape if your verb contains a ` character). Each verb-specifier can be in either tacit or explicit form: if it contains the words y or y. it is assumed to describe an explicit verb, otherwise a tacit one.

The verbs are invoked with lists as arguments and should be able to return a list of results. If you use pd , note that the verbs are not executed until pd 'show' is processed, so the values of any public variables that are referred to by an explicit verb will use the values in effect when the pd 'show' is executed. Public variables referred to in a tacit verb are frozen (using f.) when the pd for the function is issued.

Examples of function plots:

plot _10 10 ; '%'           NB. reciprocal: has a discontinuity
plot _10 10 ; 'sin`cos'     NB. two curves
plot 0.001 0.1 ; 'sin % y'  NB. sin(1/x), a busy function

3D plot example:

f=: 4 : '(cos r) % 1 + r =. x +&:*: y'
plot _4 4 100 ; _4 4 100 ; 'f'

Re-working Function Definition from Monadic to Dyadic

Sometimes it may be necessary to change the form of a function's definition to accommodate a function plot.

For instance, say we have the standard sombrero function defined to take an argument specifying the points along one side of the base of the sombrero (a single vector argument):

   sombrero0=: [: (1&o. % ]) [: %: [: +/~ *:

So, a straightforward plot might look like this:

   'surface' plot sombrero0 i:20j99
SombreroMonadicallyGenerated-sm.png

However, since this function takes only a single argument, it generates the grid of points by orthogonally adding the squares of the vector argument with +/~ so it isn't in a dyadic form. Note that a dyadic form is more general since we specify the grid by two sets of points to be combined orthogonally instead of using the single set twice.

A dyadic form might look like this:

dyasombrero=: (4 : '(1&o. % ]) %:+/*:x,y')"0/

where we put "0/ in the definition to work on the scalar elements of one vector versus each scalar element of the other vector.

So, we can make a non-square sombrero like this:

   plot _25 25 100; _15 15 100; 'dyasombrero'
DyadicSombreroByFunctionPlot-sm.png

Here's another way to make a sombrero and save it as a .PNG file. Note that we also replace the default palette with our own by re-assigning RGCLR_jzplot:

   load '~User/code/bmpPal.ijs'
   RGCLR_jzplot_=: ADJPAL
   sombrero=: 4 : '(cos % >:)x +&:*: y'
   'mesh 0' plot _4 4 100; _4 4 100; 'sombrero'
   pd 'save png C:\amisc\pix\sombreroCos.png'
94535
SombreroCos-sm.png

Keys

Plot | Verbs | Class Commands Data Options Outputs Types | Colors Fonts Keys Text YAxes | Function Multi Shape

The following options specify a key.

key - the legend

keycolor - the colors

keyfont - the font

keymarkers - key markers (diamond square circle triangle plus times line).

These are used when the keystyle includes marker or combo. The line style can be used for keys that do not correspond to a marker.

keypos - a list of up to three positions from:

  • left center right
  • top middle bottom
  • inside outside

First-letter abbreviations are supported. The default is lti, or equivalently: left top inside.

Possible key placements are:

horizontal style:     XXX
                     +---+
                     |   |
                     +---+
                      XXX

vertical style:    X +---+ X
                   X |   | X
                   X +---+ X

and similarly for inside keys.

keystyle - a list of up to four styles from:

  • left right
  • boxed open
  • vertical horizontal
  • thin fat marker combo

The marker style uses markers and the combo style uses markers and lines through the markers. The markers used are from keymarkers if given, otherwise from the standard markers.

First-letter abbreviations are supported. The default is lbvt, or equivalently: left boxed vertical thin.

Example

pd 'key Canada China India Japan USA'
pd 'keyfont Arial 8'
pd 'keypos boxed right'
pd 'keystyle for'

Layout

Each plot requires the calculation of a series of boxes (rectangular screen areas).

These are of two types:

  • frame boxes determine the frame in which the next sequence of plot commands operates.
  • item boxes determine the position of specific graphic items.

User Specified

Calculations are done automatically, but some cases can be specified by the user. These are:

  • Plot Box - isigraph window size, or the parameter to the eps or pdf commands.
  • Sub Box - parameter to the sub command.
  • Draw Box - parameter to the new or use commands.
  • Key Box - position determined by parameters to the keypos option.

Layout Calculations

The layout calculations then determine the frame boxes, in decreasing size:

1. Plot Box, Pxywh - entire graphic window.

2. Sub Box, Sxywh - a subset of Pxywh.

3. Draw Box, Dxywh - area used for the specific plot. If there is only one plot and it takes the entire window, then it is the same as the Sub Plot Box.

The following item boxes are then calculated and positioned so as to avoid overlaps:

  • Title Box, Txywh - for the Title, at the top.
  • Y Caption Box, Yxywh - for the Y Caption, on the left.
  • Y2 Caption Box, Y2xywh - for the second Y axis Caption, on the right.
  • X Caption Box, Xxywh - for the X Caption, at the bottom

4. The inside area remaining is the Out Box, Oxywh, the area available for drawing an outside key. In this case, the key item box is calculated:

  • Key Box, Kxywh - for drawing keys. Positioned now only if it is an outside key.

5. Label Box, Lxywh - area that remains after positioning the outside key item boxe. Labels are drawn in this box.

6. Frame Box, Fxywh - area in which the plot axes are drawn.

7. Graf Box, Gxywh - area in which the data is plotted.

  • If there is an extended frame, it is slightly smaller than the frame. In this case ticmarks appear in the Frame Box, but do not intrude into the Graf Box.
  • Otherwise, it is the same as the Frame Box. Ticmarks will intrude into the drawing area.

8. An inside Key Box is drawn after drawing the rest of the plot.

Multi

Plot | Verbs | Class Commands Data Options Outputs Types | Colors Fonts Keys Text YAxes | Function Multi Shape

The multi command creates a multiplot in the current subwindow, sets plot defaults.

A multiplot is an array of plots that typically have their axes linked in some way. The commands xgroup and ygroup link x and y axes.

  • If two plots have the same xgroup value, then their x-axes have the same range. If the plots are also in the same column, then the x-axes are lined up and have the same labels.
  • If two plots have the same ygroup value, then their y-axes have the same range. If the plots are also in the same row, then the y-axes are lined up and have the same labels.

Apart from linking axes, each plot is drawn independently.

The parameter to multi has two forms:

1. a pair of numbers: rows, columns. This sets up a multiplot array using equal divisions of the current window for each element of the shape.

For example:

pd 'multi 2 3'

creates a 2 row by 3 column multiplot.

2. a pair of lists, separated by comma: relative size of each row, relative size of each column

For example:

pd 'multi 4 2, 1 1 2'

creates a 2 row by 3 column multiplot. The first row has twice the height of the second, and the last column has twice the width of the first two columns.

Options

The multi command should be followed by zero or more options, then the data for the multiplot. The options are the same as before, with the following extensions:

Axis groups

xgroup sets the xgroups for the multiplots.

pd 'xgroup keylist'

The default for a multiplot of shape r c is:

pd 'xgroup ',": ,i. r,c'

Here, keylist is either a single number, or a list of length c, or list of length r * c. Plots with the same key value are drawn to the same x group.

ygroup sets the ygroups for the multiplots.

pd 'ygroup keylist'

The default for a multiplot of shape r c is:

pd 'ygroup ',": ,i. r,c'

Here, keylist is either a single number, or a list of length r, or list of length r * c. Plots with the same key value are drawn to the same y group.

For example:

a) all graphs independent (the default)

pd 'xgroup ',": ,i.r,c'
pd 'ygroup ',": ,i.r,c'

b) all graphs in a row have the same y axis and all graphs in a column the same x axis

pd 'xgroup ',": i.c
pd 'ygroup ',": i.r

c) all graphs with the same axes.

pd 'xgroup 0'
pd 'ygroup 0'

d) A cross shaped pattern:

pd 'xgroup 0 1 0 2 1 3 0 1 0'
pd 'ygroup 0 1 0 2 2 2 0 3 0'

Captions

The following gives captions for each column, and similarly for each row:

pd 'xcaption "col 1" "col 2" "col3"'

Keys

An initial Key definition is for the entire multiplot and must be an outside key.

Each plot may also have its own Key definition.

Data

The data for a multiplot is a boxed list, with one item for each plot.

Each item is either a 2-element list, or a 2-column table of: options;data, where:

  • option is a list of options, either as a LF or ';' delimited list, or as a matrix. These options are applied in addition to any options given already. The option list may include text commmands, but other commands are ignored. Second Y axes are not supported in multiplots, and font commands other than symbolfont and textfont are applied to each subplot.
  • data is a data set in the normal form for pd.

Restrictions

Second Y axes and 3D plots are not yet supported in multiplots.

Navigator

Plot | Verbs | Class Commands Data Options Outputs Types | Colors Fonts Keys Text YAxes | Function Multi Shape

Options

Plot | Verbs | Class Commands Data Options Outputs Types | Colors Fonts Keys Text YAxes | Function Multi Shape

Plot options and their defaults are shown below.

The defaults are set whenever you use the 'reset' or 'new' commands and are defined in script

  • ~system\classes\plot\plotdefs.ijs
  • ~addons\graphics\plot\plotdefs.ijs (for J8)

To customize the defaults, create a script with the same name in your config directory, i.e. with name ~config\plotdefs.ijs, and enter any changed default options. Option values are stored as uppercase global variables. For example, to default to axes without frames or grids, enter the following into your plotdefs.ijs script:

AXES=: 1
FRAME=: 0
GRIDS=: 0

Options are specified by providing the option name followed by its argument. Several options can be given at one time, separated by semicolons. For example:

pd 'title My Graph;ycaption Weight (kg);color blue,red'

Multiple character strings can be specified for options of type c such as color,key, xlabel and xcaption, using commas or spaces to delimit them. If the strings contain spaces and/or commas, enclose them double quotes first. For example:

pd 'key wool,cotton,nylon'
pd 'key "wool blanket" "cotton buds"'
pd 'xlabel "Fri, 5 Jun","Sat, 6 Jun","Sun, 7 Jun","Mon, 8 Jun"

Titles and subtitles may take more than one line, with lines separated by the line break tag <br/>. For example:

pd 'title First line (of title)<br/>Second line'

For more examples of option syntax run the Plot Demo (Studio|Demos...|plot) and view the plot definitions (Options|View Definition).

Option Type Default Description
aspect n ratio of graphics height to width (default 1 for pie or radar).
axes b 0 0 if x,y axes are shown (default off since plot is framed)
axiscolor color BLACK axis color
backcolor color WHITE background color
bandcolor colors band color scheme, see Plot Colors
barwidth n 0.75 width of bar in barchart (in range 0-1)
border b 0 if a border is drawn
bordersize n 8 size of border (isigraph units)
boxed b 1 if drawn in a box (3D only)
captionfont font Arial 13 (windows) font for x and y captions
clear b 1 if clear the background before drawing plot
color colors plot colors, see Plot Colors
contourlevels n 20 number of levels in contour plot
edgecolor colors BLACK edge color (ellipse, pie, poly, rect)
edgesize n 1 pen size of edges
forecolor color BLACK foreground color (for axes, text)
frame b 1 if plot is framed
framebackcolor color [#backcolor ] background color of frame area
framestyle n in=inner, out=outer frame, default based on plot type
graphbackcolor color [#framecolor ] background color of graph area
gridcolor color GRAY grid line color
grids b 1 1 if x, y grids are shown
guidesize n 1 pen size of guides (axes and tic marks)
itemcolor colors item color scheme, see Plot Colors
key c [#none ] key legend, see Plot Keys
keycolor colors key color scheme, see Plot Colors
keyfont font Arial 9 key font
keypos c lti key position, see Plot Keys
keystyle c lbvt key style, see Plot Keys
labelfont font Arial 9 font for labels
labels b 1 1[1] if x,y[,z] labels shown
markers c markers (diamond square circle triangle plus times)
markersize n 1 marker size
mesh b 1 if a mesh is drawn (3D only)
output c isi/gtk/pdf output used by plot or pd 'show'
orientation n 2 1=portrait, 2=landscape (printing only)
originxlabel n 0 if show 0 label at axis intersection
penpattern see plotdefs patterns used by pen styles
pensize n 1 pensize for lines, other than edges and guides
penstyle n 0 index into penpattern
piepercent n 0 [#none ] set default pie labels as percentages
plotcaption c Plot plot form caption
polar b 0 if a polar plot, data is r;theta (2D only)
printmargin v 1440 print margins in twips - left,top,right,bottom (default is 1 inch -- A twip is a "twentieth of a point". A point is approximately 1/72 of an inch and in computer systems a twip is considered to be exactly 1/1440 of an inch)
printwindow v 0 0 1000 1000 print window, bottom left, top right
rtic v [#none ] r tics (#major,#minor) (radar plot only)
rulecolor color BLACK rule color
rulesize n 1 rule size
separator c separator for char matrix entries
singtoler n 10 singularity tolerance for function plots
subtitle s [#none ] subtitle text
subtitlecolor color BLACK subtitle color
subtitlefont c Arial 14 subtitle font
symbolcolor colors BLACK symbol color
symbolfont font Symbol 9 symbol font used in point plots
symbols c symbols (square triangle inverted-triangle clubs diamonds hearts)
textcolor color BLACK text color
textfont c Arial 13 font for output from text commands
ticmajor n 12 size of major tic marks
ticminor n 8 size of minor tic marks
tics v 1 1[1] if x,y[,z] tic marks shown
ticstyle c in in=inner out=outer tics
title s [#none ] title text
titlecolor color BLACK title color
titlefont c Arial 15 title font
type c line plot type (see Plot Types)
viewcenter 0 0 0 position of plot center (3D only)
viewpoint 1.6 _2.4 1.5 position of observer (3D only)
viewsize 1 1 0.5 relative sizes of viewbox
viewup 0 0 1 upwards direction (3D only)
visible b 1 if plot is displayed
xcaption* c [#none ] x caption (the text shown along the axis)
xgridpattern* 3 5 x grid pattern
xgroup* [#none ] x group (multiplot only)
xfuncres* n [#none ] x resolution for function plots
xint* n [#none ] position of x-intercept
xlabel* c [#none ] x labels (one label per tic position)
xlog* n 0 if log applied to x values
xrange* [#none ] range of x data - low,high
xtic* [#none ] x tic - (major interval),minor count
xticpos* [#none ] x tic positions

*Options whose names begin with 'x' apply to the x-axis; similar options apply to the y and z axes.


Type Description
b boolean 0 or 1
c character string
color[s] color or color matrix - given by name or values
font font specification
n number
s character string, or
-delimited strings
v numeric list

Outputs

Plot | Verbs | Class Commands Data Options Outputs Types | Colors Fonts Keys Text YAxes | Function Multi Shape

Plot supports several outputs:

  • isigraph window (Only in J6, the default if not J console)
  • GTK window (the default for JGTK)
  • EPS file
  • PDF file (the default under J console in Mac and Windows)
  • HTML5 canvas element (the default for JHS)
  • Cairo graphic (png image file, the default under J console if supported)
  • QT window (the default for QT)
  • QTC (image file, requires QT addon but also works under jconsole)

The isigraph window may be printed, or copied to the clipboard, bmp or emf file.

Some outputs are only supported under a particular J release, see Plot/Commands for further details.

Display

For EPS and PDF, Plot attempts to display the plot using the viewers defined in Edit|Configure|External Programs. For example, GSView can be used for both formats. If you use this, it is suggested that you include the -e option that enables a new image to be drawn in the same window. This means that you can experiment with drawing plots, each appearing in the same GSView window. For example, your configuration might be:

c:\program files\ghostgum\gsview\gsview32.exe -e

You can use Adobe Reader to read PDF files, but note that if a file is already open in Adobe, then you cannot write to it again. In this case, close the file in Adobe before re-running the plot.

Calculation

The plot calculation is the same for all methods, except only when calculating font metrics. For a discussion of this, see Fonts, and in particular the discussion on fontscale.

Note that drawings to these outputs are made independently, so there may be minor differences between them. For example, one plot may display more ticmarks than another.

Typically, if you draw to outputs with the same number of units, e.g. the defaults of 480 x 360 pixels in isigraph, and 480 x 360 points in EPS and PDF, then your plots will be essentially the same. You may notice differences if you choose different sized outputs, since each plot is fitted to the space available.

Shape

Plot | Verbs | Class Commands Data Options Outputs Types | Colors Fonts Keys Text YAxes | Function Multi Shape

The sub plot command takes a parameter in one of three forms:

  • window
  • shape
  • sizes

A window parameter is the 4 numbers: xy of the bottom left corner, xy of the upper right corner. This creates a single subwindow of this size.

A position with an x suffix is in drawing units (pixels if output to screen). For example, a window of 0 0 100x 200x is the lower left 100 x 200 pixels.

A negative position counts from the end, offset by 1, so that -101x -201x -1x -1x is the 100 x 200 pixels at the top right corner.

For example, create a new sub plot window with xy position 100 100, and of size 400 by 600:

pd 'sub 100 100 500 700'

A shape parameter is the two numbers: rows, columns. This sets up an array of plots using equal divisions of the current window for each element of the shape.

For example:

pd 'sub 2 4'

will create an array of two equal depth rows and four equal width columns.

A sizes parameter is the lists, separated by comma: relative size of each row, relative size of each column. This creates an array of plots of the given relative sizes.

For example:

pd 'sub 2 1, 1 2 3 4'

will give an array in which the first row is twice the height of the second, and in which the columns have widths in ratio 1 to 2 to 3 to 4. Note that the comma acts as a separator in the string.

Subsequent Commands

After subwindows are created, subsequent commands new, use, sub, multi are relative to each subwindow in ravel order.

For example, the following creates a 2 by 3 array of subwindows, then draws plots in each. The second and last plots are blank.

pd 'sub 2 3'
pd 'new'
pd {options}
pd {data}
pd 'use'
pd 'use'
pd {options}
pd {data}
pd 'use'
pd {options}
pd {data}
pd 'use'
pd {options}
pd {data}
pd 'endsub'

Source

Plot | Verbs | Class Commands Data Options Outputs Types | Colors Fonts Keys Text YAxes | Function Multi Shape

The following is an overview of the plot source. To access this from the Project Manager, copy to the source into any directory, preserving subdirectories, and define a folder Plot that points to the source directory.

The source is in three subdirectories:

  • base has the core utilities
  • out has the output definitions (isi, eps and pdf)
  • type has code for the specific plot types, 2d and 3d

Main Subdirectories

base\pd

This defines the core user function, pd .

Input commands are stored in the Pcmd command buffer, with minimal parsing.

Output commands activate drawing. These call output verbs isi_show , pdf_show etc. Output commands are not stored in Pcmd .

base\make

This defines the core plotting routine, make . This is called by the output verbs, with an argument of output type and plot size. Output type is used only for determining font metrics.

The output of make is a global Plot that defines the plot. The output verbs then step through this global to create the actual drawing.

make method:

1. the Pcmd block is split into new or use command blocks. Each such is drawn independently by makenew . 1. makenew first determines several values for the command block, including dimensions, data, axes, text.

These in turn are used to determine the plot decorations (labels, ticmarks etc).

Each command block is then split into type blocks, and each such is drawn by maketype .

maketype then sets the remaning plot options, and calculates the plots for each type.

Other Subdirectories

base\axis axis labels and ticmarks

base\font all font handling

base\key keys

base\layout main layout calculations, see Layout

Text

Plot | Verbs | Class Commands Data Options Outputs Types | Colors Fonts Keys Text YAxes | Function Multi Shape

Text can be written directly to the plot.

Text commands are processed after all other commands, so that the text overwrites the display.

Use textcolor to specify the color, and textfont to specify the font, for example:

pd 'textcolor RED'
pd 'textfont Arial 20 Bold'

See also plot Fonts.

To specify the text and position, use commands text, textc and textr for left justified, centered, and right justified text. The parameter is: position text

The position is the x and y position, relative to the current drawing box.

Text is drawn with the given position at the top. Thus for left-justified text, the position is the top left corner of the output.

  • an ordinary number is on a scale from 0 to 1000, with 0 0 at the bottom left.
  • a number with an x suffix such as 50x is in pixels (or drawing units)
  • a negative number (either as -50 or _50)

Added in plot 1.0.188 -

  • positions may have a p suffix which indicates that the x,y values correspond to the data. This only works for plot types where x,y data values can be mapped to axis positions. For this, the text is centered vertically on the y position.

Examples

pd 'text 100 200 market value'

writes text left justified at position 100 200 inside the current drawing box, considered to be of size 1000 1000.

pd 'text 50x 100x market value'

writes text left justified at position 50 100 pixels inside the current drawing box.

pd 'textr -51x 100x market value'

writes text right justified at position 50 100 pixels inside the current drawing box. The x position is measured from the right of the drawing box, offset by 1.

pd 'text 2p 3p market value'

writes text at data values 2,3. The text is left justified to x=2, and vertically centered at y=3.

Types

Plot | Verbs | Class Commands Data Options Outputs Types | Colors Fonts Keys Text YAxes | Function Multi Shape

Plot types are:

Type 2D 3D Description
area x shows area under one or more lines
bar x bar chart
contour x contour plot (2D representation of 3D data)
density x density plot (2D representation of 3D data)
dot x dot plot
errorbar x error bars
hilo x hi - lo plot
line x x line plot (3D if xyz values given)
fbar x floating bar chart
marker x marker plot
pie x pie chart (multiple pies if table of data)
point x point plot (same as dot, retained for compatibility)
poly x polygon plot
radar x radar plot
sbar x stacked bar chart
stick x x stick plot (vertical bars)
symbol x symbol (character) plot
surface x surface plot
wire x wire surface plot

Verbs

Plot | Verbs | Class Commands Data Options Outputs Types | Colors Fonts Keys Text YAxes | Function Multi Shape

Public verbs are pd and plot.

  • pd is the low-level verb that handles all calls to Plot.
  • plot is a cover verb for pd that will handle most simple uses of Plot.

pd

pd is the low-level verb that handles all calls to Plot. It has three types of argument:

commands set up and show a plot
options specify plot type, colors etc
data data used in the plot

Commands and options are given in a character list, delimited by semicolons. Data is a numeric or boxed array.

For example:

load 'plot numeric trig'        NB. load plot and some utilities
pd 'reset'                      NB. command reset
pd 'textc 500 950 My Plot'      NB. command textc
pd 'type line'                  NB. option type
pd cos steps 0 8 100            NB. data
pd 'show'                       NB. command show
pd 'clip'                       NB. command clip
pd 'print'                      NB. command print

Plot options should be given before the data to which they apply. Options can be redefined for new data, e.g.

pd 'reset'
pd 'color red'
pd 1 2 3                        NB. data drawn in red
pd 'color blue'
pd 2 3 5                        NB. data drawn in blue
pd 'show'

plot

plot is a cover for pd. For example, the following loads the plot system and draws a simple plot.

load 'plot'
plot */~ i:20

The optional left argument is a list of pd commands and options, delimited by semicolons. The right argument is data.

The first command may be a plot type, e.g. the following are equivalent:

'bar' plot data
'type bar' plot data

plot and pd may be used together, for example:

'bar;itemcolor red,green' plot >:?2 6$10      NB. draw a barchart
pd 'print'                                    NB. print it

YAxes

Plot | Verbs | Class Commands Data Options Outputs Types | Colors Fonts Keys Text YAxes | Function Multi Shape

By default, Plot writes y labels only to a single y-axis, typically shown to the left.

To create an axis on the right, use option y2axis .

Label options or data given before option y2axis , are applied to the left y-axis, and label options and data given after are applied to the right y-axis. The x scaling is the same for both.

For example:

dat=. i:2j30
pd 'reset'
pd (;sin) dat
pd 'y2axis'
pd (;^) dat
pd 'show'