J gives you several ways to draw
pictures. The Plot Package is a quick
but powerful way to display datasets in 2D or 3D form.If you want to draw your own graphics, you
can use the gl2 library for 2D graphics, or OpenGL for 3D.

To see what J Plot can do, go to the menu bar
in a J session and click down to Studio|Demos|plot.A Plot window will pop up, on whose menu bar
pulldowns labeled 2D, 3D, Multi, Styles, and Gallery contain lists of demo
plots. Click on one and you will
immediately see the plot. When you find
an interesting one, you may click Options|View Definition to see the
commands that created it.

The Plot Package has two interfaces:
lightning-fast (the plot verb) and fast (the pd
verb). pd
lets you build a custom plot containing multiple datasets and options.The picture described by plot 3 1 4 1 5 9
could have been built with

pd 'reset'

pd 'type
line'

pd 3
1 4 1 5 9

pd 'show'

plot and pd make up the
Plot Package, which I will refer to simply as Plot.

Plot has a great variety of options which you
can find listed in the User Guide. Here
I will give enough of an overview to get started.If you need a feature for your plot, there's
a good chance it's described in the User Guide.
If you need to direct your plot to PostScript or to a control on a form,
the User Guide explains that too.

Plot accepts a series of commands, options,
and data. Commands
are actions taken independent of any data: setting the size of the plot
window(s), writing annotation text, and the like.Options, which
include things like axis scaling and color selection, control the
interpretation of subsequent data, which is added
to the plot using whatever options are in effect when the data is
encountered. A single plot may contain
multiple sets of data with different options.

The most important option
is the type of plot: surface
or wire
to display 3-D data, line to graph 2-D or 3D data, symbol
and dot to plot points individually, and a variety
of types to produce bar charts, pie charts, error bars, and many others.

Colors

The components of a plot
have different colors which you can specify.
A color is given either as a 3-item list of red,green,blue intensity in
the range 0-255, or as a name taken from J's list in system\packages\color\colortab.ijs.Names of colors are not case-sensitive.The standard colors
for plot are BLUE, RED, GREEN,
PURPLE,
FUCHSIA,
OLIVE,
TEAL,
YELLOW,
MEDIUMBLUE,
AQUA,
BROWN,
and GRAY.

The background of
the plot is made up of two parts, the graph background
which is the canvas the plot is drawn on, and the frame
background which surrounds the graph background, filling out the
window. These colors can be set
simultaneously with

backcolor color_spec

The default is backcolor 255 255 255
or, equivalently, backcolor WHITE.The components of the background can be set
individually with

framebackcolor color_spec

graphbackcolor color_spec

Most plotted data is drawn with the item colors. The
data is broken into sets of points, and the item colors are assigned to the
sets sequentially. By default the item
colors are the standard colors; they can be set by

itemcolor color_spec,color_spec...

The list of item colors can be as long as you
want; it recycles as needed.

Certain plot types, such as density,
derive the plotted colors from the data.
For these plots you use

bandcolor color_spec,color_spec...

to specify the colors used for the bands of
data.

Other components have their own colors, set by
the following commands whose names are mostly self-explanatory: axiscolor,
captioncolor,
edgecolor
(for edges of filled regions), gridcolor, keycolor
(a list, used for legend boxes), rulecolor, symbolcolor
(for symbol plots), textcolor, and titlecolor.

Fonts

You can select the font for
the different kinds of text drawing. The
commands are captionfont, keyfont,
labelfont,
symbolfont,
textfont,
and titlefont.
An example is

titlefont Arial 18

Postscript Type 1 fonts are also supported.

Titles, Captions, and Labels

The title
of the plot is drawn above the plot. You
give the title with

title
title_text

titlecolor and titlefont
apply to the title.

A caption
is a character string displayed running parallel to an axis, and can be had
with

Ccaption
caption_text

(C
is replaced by x, y, or z
to select the coordinate), where caption_text
should be enclosed in double-quotes if it contains spaces.captioncolor and captionfont
apply to captions.

Labeling
the axes means marking them to indicate coordinate values and is controlled by

labels xonyon [zon]

(default 1 1) to turn
labeling on or off. By default the
labels are just the numeric values of the coordinates at the tic marks, but you
can use

Clabel
label1label2...

to specify the label at each tic.If labeln
contains spaces, it should be enclosed in double-quotes.You can specify the coordinates at which
labels are to be shown with

Cticpos positions

or you can apply labels at regular intervals
with

Ctic label_intervaltics_between_labels

which will write a label at intervals of label_interval, and add tics_between_labels unlabeled tics between
labeled tics. The plot will be scaled to
match the range of your data unless you specify the range of the coordinate
with

Crange minmax

labelcolor and labelfont
apply to labels.

Annotation (Text in the Drawing Area)

Annotation text is given by
the text options:

textcolor color

where color
is red,green,blue or a name such as RED;

textfont font_namesize

to select the font;

text xposypostext

textc xposypostext

textr xposypostext

to draw text
at the given position, left-aligned, centered, or right-aligned.

Commands, options, and data
are all added to the plot using the monadic pd
verb. Character operands to pd
are interpreted as commands or options with the format name valuewhere name
identifies the command/option, which is set to the (optional) value.
Multiple commands/options can be given to pd,
either as a list of boxed strings, or as one long string with semicolons used
as a separator between command/options.

Numeric operands to pd
are data: one or more sets of points, where a
point comprises a dependent variable and one or
two independent variablesNormally data will be a list of boxes, x;y
for 2-D data or x;y;z for 3-D data.The last item (y
for 2-D, z for 3-D) is the dependent variable
whose values correspond to the independent variables given by the previous
items. We can distinguish 3 types of
plot: 2-D line plots, 3-D line plots, and surface plots.

2-D Line Plots

The dependent variable y
may be a list or an array. Each 1-cell
of y
gives a set of points, and each set is plotted with a different item
color. x
may have the same shape as y, or x may be a list with
the shape of a 1-cell of y in which case it is repeated for each 1-cell
of y .

3-D Line and Point Plots

The dependent variable z
may be a list or an array. Each 1-cell
of z
gives a set of points, and each set is plotted with a different item
color. x
and y must each be a list, with the shape of a 1-cell
of z,
which is repeated for each 1-cell of z.

surface and wire
Plots (3-D)

The dependent variable z
is an array. x
may have the same shape as z, or be a list with one atom for each row of z:
the atom is repeated across the row. y
may have the same shape as z, or be a list with one atom for each column of z:
the atom is repeated down the column.

Unboxed operands to pd

The boxing can be omitted from a data operand
to pd,
in which case it gives values of the dependent variable (y
for 2-D, z
for 3-D) and the independent variables are taken to be integers starting
at 0. Or, the operand can be a complex
list in which case the real parts are x and the
imaginary parts are y .

Control Commands to pd:
Starting and Ending a Plot

The first command in a plot
should be pd 'reset'.After you have sent all your data through pd,
your last command should be pd 'show' which causes the plot to be
displayed.

If your plot does not require multiple
datasets with different options, you can display the whole thing with one use
of the plot verb:

commands_and_options plot data

plot starts a new plot, sends the commands_and_options through pd,
sends the data
through pd, and issues pd 'show'
to display the result. The axes will be
scaled to fit your data. If data is made up of a rank-2 array of
boxes each of which contains a list of boxes, each box gives the data for a subplot: the plot window is divided into tiles based on
the shape of data,
and each atom of data
is opened revealing a list of x;y[;z] boxes containing data to be plotted in
corresponding tile. An example of
subplots is

For a simple 2-D plot of
the value of a function f evaluated at the values x,
use

plot
x ; f x

If you just want evenly-spaced values of x,
you can use the steps verb:

steps
initial_value final_value
number_of_intervals

A plot of one period of the sine function is
given by

plot (steps 0 2p1 100) ; sin steps 0 2p1 100

(2p1 is 2π).To plot two functions at the same x
values, make each function's values a row of an array:

x =.
steps 0 2p1 100

plot
x ; (sin x) ,: cos x

Using a fork, you can express this plot as

plot
(; sin,:cos) steps 0 2p1 100

For 3-D plot of a function f
evaluated on a grid of x and y values, use

plot
x ; y ; x f"0/ y

f"0/ is described in the "Make a
Table" section of the chapter "Odds and Ends".x f"0/ y evaluates f
at each combination of x and y .To plot cos(r)/(1+r) we would use

x =.
y =. steps _4 4 100

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

plot
x ; y ; x f"0/ y

Using a fork, this plot is given succinctly by

plot x
([ ; ] ; f"0/) y

The Simplest Function Plotting: Let Plot Evaluate
Your Function

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 dependent
variable in the right argument to plot or pd .The plot may be 2-D or 3-D.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].

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
commands 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 word 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.

A plot of a function with discontinuities, or
multiple functions with different domains, can be assembled using pd.If we want to plot the function 1/x (the J primitive %)
by hand rather than using function plotting as shown above, we need to plot the
negative and positive sides individually:

pd 'reset'

pd 'type
line'

pd 'color
0 0 255'

pd (^
steps _2 2 50) ; % (^ steps _2 2 50)

pd (-
^ steps _2 2 50) ; % (- ^ steps _2 2 50)

pd 'show'

Here we plotted the positive x
values, then the negative ones. We set color
to override Plot's default behavior of giving each dataset a different
color. The exponential applied to the x
values keeps the points spaced fairly uniformly along the curve.

Although we often think of one
variable as dependent and the others independent, this is our interpretation,
not a restriction in Plot. y
does not have to be a function of x: y may just
represent data measurements at values of x, or x
and y can both be parametric functions of
something else. For example, a lovely
Lissajous figure can be plotted with

The gl2 Library is a set of functions for
drawing 2D graphics into windows. There
are many more functions in this library than can be discussed here: to see the
full list, open a J session, press F1 for help, click on 'wd' at the top of the
page, then click the link for 'gl2 commands'.
It will be worth your time to read through the commands a few times to
get an idea about what's available.

To use the gl2 commands you must include them
in your program with

load 'gl2'

Because there are so many functions, they are
defined in a locale of their own, called jgl2 .To have access to the functions in jgl2,
you should include the line

coinsert 'jgl2'

at the top of each file using the gl2
commands. Alternatively, you could add jgl2
to the name of each gl2 function you use, but it is easier to use the coinsert.

Graphics are drawn into an
object called an isigraphcontrol
(the isi comes from Iverson Software, Inc., the
original name of Jsoftware, Inc.) which resides in a window.

You can choose from several ways to create an isigraph
control, depending on what features you need.
The quickest way to get one is with

load 'graph'

gopen
''

which will leave you ready for drawing with an
isigraph
control 150 pixels on a side. If you
want to specify your own options for the parent window or isigraph
control, you can bypass the graph package, using instead a line like

wd 'pc x closeok;xywh 0 0 200 200;cc g isigraph;pas 0
0;pshow'

which will also leave you ready for
drawing. In this example, the parent
window was named x and the isigraph
control was named g with a size of 200x200 pixels.The pas 0 0
caused the parent to fit tightly around the isigraph.

If you simply want a standalone window to
display graphics in, either of the preceding methods is adequate.If you want your graphics to be part of a form which can contain other graphics controls as well
as text, sliders, selection boxes, and the like, you will want to learn how to
use the Form Editor, either by reading the User Guide or by running the
Labs. Use the Form Editor to create a
form, and include a child control of type isigraphYour gl2 commands will be drawn into this
child control.

All isigraph controls
have the same capabilities, no matter what method was used to create them.

If you have simply created
a single isigraph control for use as a display, it was
automatically selected for output when created and you do not need to do
anything more than write to it.

If you have a more complex environment, where
there are perhaps several isigraph controls in a form and many forms
open at once, you need to select the correct isigraph
control before you write to it. gl2
commands operate on the currently-selected isigraph
control.

You will issue a sequence
of glxxx verbs.(The graph library
defines verbs to interface to the glxxx
verbs, but I recommend you avoid them in the interests of performance)The pixel-writing verbs, such as glrect
and gllines, make use of the current pen (the linestyle used to draw the outline)
and the current brush (the fill style used for
the interior). The pen and brush
commands, and some of the other glxxx
verbs, use the current color, a list of RGB
(red-green-blue) values from 0 to 255.

As an example, to draw a 2-pixel-wide dashed red
line from the top-left corner to the bottom-right corner of the selected isigraph,
use

where styles
can be any of italic, bold, underline,
oem,
default,
and anglexxx
(where xxx
is the angle of the font, in tenths of a degree clockwise).size
is in points. Example:

glfont "Times New Roman" 12 italic

Next, draw the background
rectangle if any. Text itself is
transparent, in other words the background shows though the text. If you want a solid background for the text,
you must draw one. Find out how big the
text will be in pixels:

extent
=. glqextent textstring

then create a brush with the background color,
and draw the background rectangle:

glbrush '' [ glrgb red green blue

glrect xcoord,ycoord,extent

Next, set the color for the text itself:

gltextcolor '' [ glrgb redgreenblue

Finally, set the text position
in pixels and draw the text.

gltextxy xcoord,ycoord

gltext text

where text
is the character string to draw.

The settings of the
text attributes are preserved, so only the changed values need to be set for
subsequent gltext calls.

The glxxx verbs write pixels on
the drawing surface, which is a memory area that
has the size of your isigraph control.Changes to the drawing surface are not
immediately visible, lest the user be distracted by continual painting and an
incomplete picture. When you have
executed enough glxxx
commands to have a picture worth seeing, you issue

If your isigraph control
never changes size, what is displayed on the screen will be whatever you put
there with your last glpaint command.If, on the other hand, your isigraph
can be resized by the user, the display will become invalid whenever the isigraph
is resized. When this happens, the
system will signal a paint event, and you will have to recreate the
display surface. See below for a
discussion of event handling.

Supporting a resizable isigraph
window has profound effects on the design of your program.You must keep a copy of all the graphics
commands needed to regenerate the display, and for most applications you need
to keep these commands in a virtual screen space so that they don't suffer
unsightly errors in quantization when the screen size changes.

i j give the (i,j) coordinates of a
point in logical units, where i
is the horizontal coordinate and j
is the vertical coordinate. x y w h specifies a
rectangular region with one corner at (x,y) and the other at (x+w-1,y+h-1).

glclip x y w h Only pixels inside the given
rectangle will be modified by subsequent drawing commands.

glclipreset ''Turn off clip rectangle, allowing all pixels
to be overwritten by drawing commands

Setting Colors

glrgb color
; set current color

Settings That Apply to Lines (including
Borders of Filled Areas)

glpen i [style]select pen. color is taken from last glrgb
command, and the lines are drawn i
units wide. style is from the set (ps_solid, ps_dash, ps_dot, ps_dashdot, ps_dashdotdot, ps_null,
ps_insideframe)

Drawing Lines

gllines i j i j
... draw connected
lines. i j...
is 2 or more points. gllines
is the verb normally used for line-drawing.

Settings That Apply to Area-Filling Commands

glbrush ''select solid brush in current color,
i. e. fill interiors with solid fill in the color of the most recent glrgb.

glellipse x y w h draw a filled ellipse in the given rectangle
with the current pen and brush

glarc x y w h xa ya xz
yz(not wince)
draw arc on the ellipse defined by the given rectangle. Arc starts at (xa,ya)
and ends at (xz,yz). Start and end points need not lie on the
ellipse: they define a line from the center that intersects the ellipse.

Drawing Polygons

glpolygon i j i j
... draw polygon in
current pen and brush. The list of (i,j)
values are the polygon vertices.. glpolygon
is the verb normally used to draw polygons.

Settings That Apply to Text

glfont name size
styles sets font
for text commands

Drawing Text

gltext text write text using the font specified
by the most recent glfont in the color saved by the most recent gltextcolor.
Where and how the text is displayed is
affected by the gltextalign and gltextxy
commands.

gltextcolor ''the
color set by the most recentglrgb is saved as the
color to be used for text

gltextxy i j position to be used by gltext
when gltexalign specifies TA_NOUPDATECP

Bitmap Operations

glpixel i jdraw pixel at (i,j)
in current color

glpixels x y w h pixeldatawrite pixels to the given rectangle. pixeldata
is an integer per pixel with RGB values

Metafile Operations

glfile filename(only win32) set filename for subsequent glemfopen
and glemfplay.

glemfopen ''(only win32) Open the file named in the most
recent glfile command.This file will be an enhanced metafile, and
subsequent glxxx
commands will be written to this file.

glemfclose '' (only win32) Close the file opened by glemfopen ..

glemfplay x y [w h](only win32) Play the enhanced metafile named
in the most recent glfile command.x y
gives the top-left corner of the area on which the metafile will be drawn; w h give the size of the rectangle
that the metafile will be scaled to fit into, or may be omitted to display the
metafile at full size.

isigraph
controls produce events, which like all window events result in execution of
the sentence

formname_isigraphname_eventname_formlocale_
''

where formlocale
is the name of the locale the form was executed in, and the other names
identify the form, isigraph, and event type.Before execution of this sentence, the
variable sysdata is set with information about the
event. The events and their associated sysdata
are:

paint Event

The paint event is signalled
whenever the isigraph control changes size.The paint event
handler must redraw the drawing surface.
It does not need to issue glpaint to move the display surface to the
screen--that will be done automatically.

char Event

When a character is pressed while the cursor
is within an isigraph control, a char
event is produced. sysdata
is a character list giving the key that was pressed: the character itself for
printable keys, or the virtual key VK_name for a special key such as HOME or an arrow key
(look in system\packages\graphics\vkeys.ijs for the VK_name definitions).For example, sysdata is 'a' if the letter-a
key is pressed, and 21{a. if the
up-arrow is pressed. The
character in sysdata is represented in UTF-8 form, which
means that it will be encoded as a multi-character sequence if the ASCII code
is 128 or higher.

sysmodifiers is a single character
value indicating whether CTRL or SHIFT was pressed: '0'=neither, '1'=SHIFT, '2'=CTRL, '3'=SHIFT+CTRL.No event is signaled for CTRL+ASCII-character
as that is taken to be a keyboard shortcut.

Mouse Events

The mouse events are mmove,
mbldown,
mblup,
mbldbl,
mbrdown,
mbrup,
and mbrdbl, corresponding to mouse-move and
mouse-clicks (left or right button; down, up, or double-click).sysdata contains a character string which
should be converted to numeric using 0&".,
after which it will be an 8-item vector indicating the values

cursorx cursory isiwidth isiheight mbl mbr
ctrl shift

where cursorx and cursory
give the cursor position in pixels, isiwidth and isiheight
give the size of the isigraph control in pixels, and mbl,
mbr,
ctrl,
and shift give the status of the corresponding
mouse-buttons and keys at the time of the event.

Each call to a glxxx verb makes an addition
to the display list. If your calls have
small amounts of data, the overhead of updating the display list could take
much more time than the drawing to the screen.
In that case, you can see a performance improvement if you build a graphics block holding the data for several glxxx verbs and then pass
the block into J with a single call.

The graphics block will be a numeric list
which is a concatenation of graphics orders.Each graphics order replaces one call to a glxxx verb and has the
format

length_of_order,glxxx_code,data

length_of_order
is 2+$data (i. e., the length of
the graphics order including the length field).
glxxx_code
identifies the glxxx
verb that the graphics order represents: this is the code used in system\main\gl2.ijs
to define the glxxx
verb. For example, the glline
verb is defined by

glline=: 11!:2013

so the glxxx_code
for glline is 2013.data
is the operand needed by the glxxx
verb.

Once you have built the graphics block, you draw
it by executing glcmds graphicsblock .To draw the 2-pixel-wide dashed red line used
in the example above, you could issue the glrgb, glpen,
and gllines in one go with

For 3-D graphics, J
supports OpenGL, a graphics interface of great power with a manual the size of
a phonebook. If you want to learn about
it, study the manual; if you know OpenGL and want to use it in J, consult the
Labs.