1 /*
2  * $Id: graph.i,v 1.15 2011-01-09 01:17:46 dhmunro Exp $
3  * Declarations of Yorick graphics functions.
4  */
5 /* Copyright (c) 2005, The Regents of the University of California.
6  * All rights reserved.
7  * This file is part of yorick (http://yorick.sourceforge.net).
8  * Read the accompanying LICENSE file for details.
9  */
10 
11 /*= SECTION(plotout) controlling plot windows and files ====================*/
12 
13 extern window;
14 /* DOCUMENT window, n, display="host:server.screen", dpi=100/75, wait=0/1,
15                        private=0/1, hcp="hcp_filename", dump=0/1,
16                        legends=1/0, style="style_sheet_filename",
17                        width=wpixels,height=hpixels,rgb=1,
18                        parent=id,xpos=x_in_parent,ypos=y_in_parent
19 
20      select window N as the current graphics output window.  N may
21      range from 0 to 63, inclusive.  Each graphics window corresponds to
22      an X window, and optionally has its own associated hardcopy file.
23      If N is omitted, it defaults to the current coordinate system.
24 
25      The X window will appear on your default display at 75 dpi, unless
26      you specify the display and/or dpi keywords.  A dpi=100 X window
27      is larger than a dpi=75 X window; both represent the same thing
28      on paper.  Use display="",hcp="filename" to create a graphics window
29      which has no associated X window, but instead plots to a hardcopy
30      file (you should do this if you want to make plots in a non-interactive
31      batch mode).
32 
33      By default, if the X window needs to be created, the graphics area
34      will be 450x450 pixels if dpi=75, or 600x600 pixels if dpi=100,
35      representing a 6x6 inch square on hardcopy paper.  You can override
36      this default initial size using the width and height keywords.
37      These settings remain in force indefinitely; use width=0,height=0
38      to return to the default dpi-dependent behavior.  For a dpi=75,
39      landscape=0 window, width=638,height=825 displays the entire sheet
40      of hardcopy paper.  Supplying these keywords will not change the
41      size of an existing window; only newly created windows.
42 
43      By default, an X window will attempt to use shared colors, which
44      permits several Yorick graphics windows (including windows from
45      multiple instances of Yorick) to use a common palette.  You can
46      force an X window to post its own colormap (set its colormap
47      attribute) with the private=1 keyword.  You will most likely have
48      to fiddle with your window manager to understand how it handles
49      colormap focus if you do this.  Use private=0 to return to shared
50      colors.
51 
52      By default, Yorick will not wait for the X window to become visible;
53      code which creates a new window, then plots a series of frames to
54      that window should use wait=1 to assure that all frames are actually
55      plotted.
56 
57      By default, a graphics window does NOT have a hardcopy file
58      of its own -- any request for hardcopy are directed to the
59      default hardcopy file, so hardcopy output from any window goes
60      to a single file.  By specifying the hcp keyword, however, a
61      hardcopy file unique to this window will be created.  If the
62      "hcp_filename" ends in ".cgm", the hardcopy file is a binary CGM
63      file; otherwise, hardcopy files are in Postscript format.  Use
64      hcp="" to revert to the default hardcopy file (closing the window
65      specific file, if any).  The legends keyword, if present, controls
66      whether the curve legends are (legends=1, the default) or are not
67      (legends=0) dumped to the hardcopy file.  The dump keyword, if
68      present, controls whether all colors are converted to a gray scale,
69      (dump=0), or the current palette is dumped at the beginning of each
70      page of hardcopy output (dump=1, the default).  (The legends keyword
71      applies to all pictures dumped to hardcopy from this graphics
72      window.  The dump keyword applies only to the specific hardcopy
73      file defined using the hcp keyword -- use the dump keyword in the
74      hcp_file command to get the same effect in the default hardcopy
75      file.)
76 
77      Use rgb=1 to set the rgb color model when you are creating a
78      window on an 8-bit display on which you intend to use three
79      component rgb colors (see color).  This installs the 5x9x5
80      colorcube and avoids having to issue the palette command
81      after the first true color object has been drawn.
82 
83      If both display="" and hcp="", the graphics window will be
84      entirely eliminated.
85 
86      The style keyword, if present, specifies the name of a Gist style
87      sheet file; the default is "work.gs".  The style sheet determines
88      the number and location of coordinate systems, tick and label styles,
89      and the like.  Other choices include "axes.gs", "boxed.gs",
90      "work2.gs", and "boxed2.gs".
91 
92      The parent=id keyword can be used to make the yorick window a
93      subwindow of an existing window.  The id is an integer, which is
94      the system-dependent window id that must be retrieved from the
95      application which owns the parent window.  When parent= is defined,
96      xpos= and ypos= specify the offset in that window; both default to 0.
97 
98      If invoked as a function, window(...) returns the current
99      window number.
100    SEE ALSO: plsys, hcp_file, fma, hcp, redraw, palette, animate, plg,
101              winkill, gridxy, no_window, cmap, torgb
102  */
103 
winkill(n)104 func winkill(n)
105 /* DOCUMENT winkill
106          or winkill, n
107      deletes the current graphics window, or graphics window N (0-63).
108    SEE ALSO: window
109  */
110 {
111   window, n, display="", hcp="";
112 }
113 
114 extern current_window;
115 /* DOCUMENT n= current_window()
116      returns the number of the current graphics window, or -1 if none.
117  */
118 
119 extern window_geometry;
120 /* DOCUMENT window_geometry()
121          or window_geometry(win)
122      Get geometry settings of the  visible region of display window WIN (or
123      current window  if WIN is nil  or not specified).   These settings are
124      subject to change  each time the window get resized.   The result is a
125      vector of 6 doubles:
126        [DPI, ONE_PIXEL, XBIAS, YBIAS, WIDTH, HEIGHT]
127      where:
128        DPI = dot-per-inch of WIN
129        ONE_PIXEL = pixel size in NDC units
130        XBIAS = abscissa offset in NDC units
131        YBIAS = ordinate offset in NDC units
132        WIDTH = width of visible region in pixels
133        HEIGHT = height of visible region in pixels
134      Pixel coordinates (XPIX,YPIX) run  from top-left (0,0) to bottom-right
135      (WIDTH-1,HEIGHT-1).  The conversion to NDC coordinates is:
136        XNDC = XBIAS + XPIX*ONE_PIXEL;
137        YNDC = YBIAS - YPIX*ONE_PIXEL;
138 
139      If window WIN does not exists, all output values are zero.
140 
141      Notes:
142        (1) The  top/left  margin(s) used  by  Gist window  to display  some
143            message are not considered as part of the "visible" region.
144        (2) An  extra 0.5  pixel offset has  been added to  (XBIAS,YBIAS) to
145            avoid rounding errors.
146 
147    SEE ALSO: window, current_window, viewport, limits.
148  */
149 
150 extern window_select;
151 extern window_exists;
152 extern window_list;
153 /* DOCUMENT window_select(n)
154          or window_exists(n)
155          or window_list()
156 
157      The function window_select makes window number N the current one and
158      return 1 (true); unless window number N does not exists, in which case
159      the current window is left unchanged and 0 (false) is returned.
160 
161      The function window_exists returns 1 or 0 whether or not window number
162      N exists.
163 
164      The function window_list returns the list of existing windows as a
165      vector of longs or nil if no window currently exists.
166 
167    SEE ALSO: window, current_window, redraw, fma, limits, window_geometry.
168  */
169 
170 extern current_mouse;
171 local focused_window;
172 local has_mouse;
173 /* DOCUMENT current_mouse();
174          or current_mouse(win);
175          or focused_window();
176          or has_mouse();
177          or has_mouse(win);
178 
179      The function current_mouse returns the pointer position in the
180      graphics window with pointer focus as an array of double's in the
181      form [X,Y,SYS,WIN] where X and Y are the pointer coordinates in
182      the coordinate system SYS and WIN is the number of the graphics
183      window.  If no graphics window currently has the pointer focus or
184      if WIN is specified but does not match the graphics window with
185      pointer focus, the result is empty.
186 
187      The function focused_window returns the number of the graphics
188      window with pointer focus, or -1 if none.
189 
190      The function has_mouse with a void argument returns true if any
191      Yorick graphics window has the pointer focus. If WIN is
192      specified, the function has_mouse returns true if graphics window
193      WIN has the pointer focus.
194 
195      Note that the window which has the pointer focus may be different
196      from the so-called current window to which graphics commands are
197      directed.  The built-in functions `window' and `current_window'
198      (which see) can be used to set/query the current window.
199 
200    SEE ALSO: current_window, mouse, window
201  */
202 
focused_window(nil)203 func focused_window(nil)
204 {
205   m = current_mouse();
206   if (is_void(m)) return -1;
207   return long(m(4));
208 }
209 
has_mouse(win)210 func has_mouse(win)
211 {
212   return (! is_void(current_mouse(win)));
213 }
214 
215 extern viewport;
216 /* DOCUMENT port= viewport();
217      returns [xmin,xmax,ymin,ymax] of the current viewport (or 0,0,0,0
218      if currently plotting to system 0) in NDC coordinates.
219    SEE ALSO: limits, gridxy
220  */
221 
222 extern raw_style;
223 /* DOCUMENT raw_style: get_style, set_style, read_style, write_style
224      alternatives to the style= keyword of the window command which
225      allow the interpreter to set or get all the details of the
226      window style.  Read the help for get_style.
227  */
228 
229 extern set_gpath;
230 /* DOCUMENT old = set_gpath(gist_path)
231      set path (colon delimited directories) for Gist graphics package,
232      returning old path.  GIST_PATH nil or string(0) just returns old.
233  */
234 
235 extern hcp_file;
236 /* DOCUMENT hcp_file, filename, dump=0/1, ps=0/1
237      sets the default hardcopy file to FILENAME.  If FILENAME ends with
238      ".cgm", the file will be a binary CGM, otherwise it will be a
239      Postscript file.  By default, the hardcopy file name will be
240      "Aa00.ps", or "Ab00.ps" if that exists, or "Ac00.ps" if both
241      exist, and so on.  The default hardcopy file gets hardcopy from all
242      graphics windows which do not have their own specific hardcopy file
243      (see the window command).  If the dump keyword is present and non-zero,
244      the current palette will be dumped at the beginning of each frame
245      of the default hardcopy file (default behavior).  With dump=0,
246      all colors are converted to a gray scale, and the output files are
247      smaller because no palette information is included.
248      Use ps=0 to make "Aa00.cgm", "Ab00.cgm", etc by default instead of
249      Postscript.
250      The dump= and ps= settings persist until explicitly changed by a
251      second call to hcp_file; the dump=1 setting becomes the default for
252      the window command as well.
253    SEE ALSO: window, fma, hcp, plg, no_window
254  */
255 
256 extern hcp_finish;
257 /* DOCUMENT filename= hcp_finish()
258          or filename= hcp_finish(n)
259      closes the current hardcopy file and returns the filename.
260      If N is specified, closes the hcp file associated with window N
261      and returns its name; use hcp_finish(-1) to close the default
262      hardcopy file.
263    SEE ALSO: pdf_finish, window, fma, hcp, hcp_out, plg
264  */
265 
266 func hcp_out(n,keep=)
267 /* DOCUMENT hcp_out
268          or hcp_out, n
269      finishes the current hardcopy file and sends it to the printer.
270      If N is specified, prints the hcp file associated with window N;
271      use hcp_out,-1 to print the default hardcopy file.
272      Unless the KEEP keyword is supplied and non-zero, the file will
273      be deleted after it is processed by gist and sent to lpr.
274    SEE ALSO: window, fma, hcp, hcp_finish, plg
275  */
276 {
277   filename= hcp_finish(n);
278   if (filename) {
279     if (strpart(filename,-2:0)==".ps")
280       system, swrite(format=LPR_FORMAT, filename);
281     else
282       system, swrite(format=GIST_FORMAT, filename);
283     if (!keep) remove, filename;
284   }
285 }
286 
287 func no_window(name, style=)
288 /* DOCUMENT no_window
289             no_window, hcpname
290             no_window, ""
291      Set up a graphics window with no interactive display, similar to
292        window, display="", hcp=hcpname, dump=1, legends=0;
293      You can optionally supply a filename HCPNAME; if you do not, the
294      default filename will be "no_window".  If HCPNAME is "" or string(0),
295      this graphics window is killed, and the special behavior of the
296      eps and other commands (see below) is restored to normal.  Use
297      no_window if you do not want to create an interactive graphics
298      window, for example when yorick is running in batch mode and is
299      not connected to any interactive graphics devices, causing the
300      code to crash when it tries to create an interactive window.
301 
302      As a convenience, no_window accepts a style= keyword, which it will
303      pass along to the window command.  If you need to set other window
304      properties, call the window function after no_window.
305 
306      Additionally, the no_window function changes the behavior of the
307      single picture commands hcps, eps, pdf, png, jpeg (and other functions
308      based on the hcps command) to write the current drawing to the specified
309      file, then reissue a non-displaying window command.  The effect is to
310      simplify making a sequence of plots in batch mode without creating any
311      interactive graphics window.  If you want to write the whole sequence
312      into a single .ps file, you use the no_window function to set the
313      filename, then hcp or hcp_on to dump frames into the file.
314 
315      Alternatively, if you need to write one file per frame (for example
316      one png per picture to include in slides using presentation software),
317      you can call no_window, then issue the png (or similar) command just
318      before advancing to the next frame.  (Unfortunately, you cannot do
319      both -- either you are writing all the frames into one ps file, or
320      you are writing one frame per file.  Calling the single frame function
321      will close the postscript file.)
322 
323    SEE ALSO: hcps, eps, pdf, png, jpeg
324  */
325 {
326   if (is_void(name)) name = "no_window.ps";
327   extern _no_window;
328   if (!strlen(name)) {
329     _no_window = [];
330     winkill;
331   } else {
332     _no_window = name;
333     window, display="", hcp=_no_window, style=style;
334   }
335 }
336 
337 extern keybd_focus;
338 /* DOCUMENT keybd_focus, on_off
339      By default, graphics windows set a window manager hint which
340      allows them to accept keyboard focus.  With ON_OFF zero, that
341      hint will not be set when a new graphics window is created.
342      This causes the window manager to refuse to offer keyboard
343      focus to the graphics window -- very desirable, since it can't
344      accept keyboard input anyway.  With fvwm, for example, this
345      means keyboard focus can stay in the terminal window even when
346      you are mouse zooming the graphics window.  However, many
347      window managers confuse colormap focus with keyboard focus, so
348      if you set the private=1 colormap in the window function, you
349      may not be able to convince the window manager to give the
350      graphics window colormap focus since it won't give it keyboard
351      focus.  Weird.
352  */
353 
hcps(name)354 func hcps(name)
355 /* DOCUMENT hcps, name
356      writes the picture in the current graphics window to the
357      PostScript file NAME+".ps" (i.e.- the suffix .ps is added to NAME).
358      Legends are not written, but the palette is always dumped.
359      This is mostly for internal use; see png, svg, eps, or jpeg.
360    SEE ALSO: png, window, fma, hcp, hcp_finish, plg, no_window
361  */
362 {
363   if (strpart(name,-2:0)!=".ps") name+= ".ps";
364   extern hcp;
365   window, hcp=name, dump=1, legends=0;
366   hcp;
367   if (!_no_window) window, hcp="";
368   else window, display="", hcp=_no_window;
369   return name;
370 }
371 
epsi(name)372 func epsi(name)
373 /* DOCUMENT eps, name
374      writes the picture in the current graphics window to the Encapsulated
375      PostScript file NAME+".epsi" (i.e.- the suffix .epsi is added to NAME).
376      The eps function requires the ps2epsi utility which comes with the
377      project GNU Ghostscript program.  Any hardcopy file associated with
378      the current window is first closed, but the default hardcopy file is
379      unaffected.  As a side effect, legends are turned off and color table
380      dumping is turned on for the current window.
381      The external variable PS2EPSI_FORMAT contains the format for the
382      command to start the ps2epsi program.
383    SEE ALSO: eps, hcps, window, fma, hcp, hcp_finish, plg, no_window
384  */
385 {
386   name= hcps(name);
387   system, swrite(format=PS2EPSI_FORMAT, name);
388   remove, name;
389 }
390 if (is_void(PS2EPSI_FORMAT)) PS2EPSI_FORMAT= "ps2epsi %s";
391 
392 func eps(name, pdf=)
393 /* DOCUMENT eps, name
394      writes the picture in the current graphics window to the Encapsulated
395      PostScript file NAME+".eps" (i.e.- the suffix .eps is added to NAME).
396      This function requires ghostscript.  Any hardcopy file associated with
397      the current window is first closed, but the default hardcopy file is
398      unaffected.  As a side effect, legends are turned off and color table
399      dumping is turned on for the current window.
400      The external variable EPSGS_CMD contains the command to start
401      ghostscript.
402 
403      See help,pdf for advice about hairline artifacts between filled
404      polygons in plf or plfc output.
405 
406    SEE ALSO: pdf, png, svg, jpeg, epsi, hcps, window, fma, hcp, no_window, plg
407  */
408 {
409   if (strpart(name, -3:0) == ".eps") name = strpart(name,1:-4);
410   /* dump the postscript file */
411   psname = hcps(name+".pseps");
412 
413   /* begin copying to the eps file */
414   f = create(name+".eps");
415   g = open(psname);
416   write, f, format="%s\n", "%!PS-Adobe-2.0 EPSF-1.2";
417   rdline, g;
418   line = rdline(g);
419   if (strmatch(line,"% EPSF-3.0")) line = rdline(g); /* old ps.ps bug */
420   for (i=1 ; i<=4 ; i++) {  /* Title For CreationDate Creator */
421     write, f, format="%s\n", line;
422     line = rdline(g);
423   }
424 
425   /* use ghostscript to compute true bounding box */
426   bbname = name+".bbeps";
427   for (;;) {
428     gscmd = EPSGS_CMD+" -sDEVICE=bbox -sOutputFile=- \"%s\" >>\"%s\" 2>&1";
429     system, swrite(format=gscmd, psname, bbname);
430     bb = rdline(open(bbname), 20);
431     bb = bb(where(bb));
432     remove, bbname;
433     tok = strtok(bb);
434     list = where(tok(1,) == "%%HiResBoundingBox:");
435     if (!numberof(list)) {
436       list = where(tok(1,) == "%%BoundingBox:");
437     }
438     xmn = ymn = xmx = ymx = 0.;
439     if (!numberof(list) || sread(tok(2,list(1)), xmn, ymn, xmx, ymx) != 4) {
440       /* Ghostscript 7.07 bbox fails if -dSAFER present,
441        * Ghostscript 8.61 bbox fails if -dSAFER absent
442        * the 8.61 failure gives an incorrect bounding box, so will never
443        *   reach this workaround code
444        * the 7.07 bug produces no BoundingBox comments at all, so will
445        *   reach here
446        * therefore, -dSAFER should be present in EPSGS_CMD initially
447        *   and be removed for a second try with code that works in 7.07
448        */
449       if (strpart(EPSGS_CMD, -7:0) == " -dSAFER")
450         EPSGS_CMD = strpart(EPSGS_CMD, 1:-8);
451       else
452         error, "ghostscript sDEVICE=bbox bug workaround failed";
453     }
454     break;
455   }
456 
457   if (!pdf) {
458     write, f, format="%s\n", bb;
459     write, f, format="%s\n", "save countdictstack mark newpath "+
460       "/showpage {} def /setpagedevice {pop} def";
461   } else {
462     /* concept from epstopdf perl script
463      * by Sebastian Rahtz and Heiko Oberdiek,
464      * distributed as part of the TeTeX package, see http://www.tug.org
465      */
466     write, f, format="%%BoundingBox: 0 0 %f %f\n", xmx-xmn, ymx-ymn;
467     write, f, format="<< /PageSize [ %f %f ] >> setpagedevice\n",
468       xmx-xmn, ymx-ymn;
469     write, f, format="gsave %f %f translate\n",
470       -xmn, -ymn;
471   }
472   write, f, format="%s\n", "%%EndProlog";
473   while (line) {
474     if (strpart(line,1:2)!="%%")
475       write, f, format="%s\n", line;
476     line = rdline(g);
477   }
478 
479   close, g;
480   remove, psname;
481 
482   write, f, format="%s\n", "%%Trailer";
483   if (!pdf) {
484     write, f, format="%s\n", "cleartomark "+
485       "countdictstack exch sub { end } repeat restore";
486   } else {
487     write, f, format="%s\n", "grestore";
488   }
489   write, f, format="%s\n", "%%EOF";
490   close, f;
491   return name+".eps";
492 }
493 /* -dSAFER option should be present (see above) and must be last */
494 if (is_void(EPSGS_CMD)) EPSGS_CMD= "gs -q -dNOPAUSE -dBATCH -dSAFER";
495 
pdf(name)496 func pdf(name)
497 /* DOCUMENT pdf, name
498      writes the picture in the current graphics window to the Adobe PDF
499      file NAME+".pdf" (i.e.- the suffix .pdf is added to NAME).  The
500      pdf file is intended to be imported into MS PowerPoint or other
501      commercial presentation software, or into in pdftex or pdflatex
502      documents; it is cropped.  The result should be equivalent to
503      running the epstopdf utility (which comes with TeX, see www.tug.org)
504      on the eps file produced by the eps command.
505      This function requires ghostscript.  Any hardcopy file associated with
506      the current window is first closed, but the default hardcopy file is
507      unaffected.  As a side effect, legends are turned off and color table
508      dumping is turned on for the current window.
509      The external variable EPSGS_CMD contains the command to start
510      ghostscript.
511 
512      You may have problems with hairline artifacts in plf or plfc output.
513      This turns out to be caused by anti-aliasing; the files are correct,
514      but modern rendering engines create the artifacts by trying to
515      soften pixelated edges.  If you can figure out how to turn off
516      antialiasing in your rendering software, you can generally get
517      rid of the hairlines.  The downside is, that text an diagonal lines
518      will have jagged edges and look worse.  What you want is a very
519      high resolution display, and turn off anti-aliasing (since it isn't
520      so necessary).
521 
522    SEE ALSO: png, svg, jpeg, eps, hcps, window, fma, hcp, no_window, plg,
523              pdf_finish
524  */
525 {
526   if (strpart(name, -3:0) == ".pdf") name = strpart(name,1:-4);
527   /* first run ghostscript to produce an eps translated to (0,0) */
528   psname = eps(name+".pdf", pdf=1);
529   /* second run ghostscript to produce the cropped pdf */
530   gscmd = EPSGS_CMD+" -sDEVICE=pdfwrite -sOutputFile=\"%s\" \"%s\"";
531   system, swrite(format=gscmd, name+".pdf", psname);
532   remove, psname;
533 }
534 
pdf_finish(n)535 func pdf_finish(n)
536 /* DOCUMENT pdf_finish
537          or pdf_finish, n
538          or pdf_finish(n)
539      closes the current hardcopy file and converts it to pdf format.
540      If N is specified, closes the hcp file associated with window N
541      and converts it; use pdf_finish,-1 to close the default
542      hardcopy file.  Called as a function, pdf_finish returns the name
543      of the pdf file created.
544      The pdf_finish function only works if the hcp file is a Postscript
545      file, with a name ending in ".ps".  The pdf file will have the same
546      name, except ending in ".pdf".
547    SEE ALSO: pdf, hcp_finish
548  */
549 {
550   psname = hcp_finish(n);
551   if (!psname || strpart(psname, -2:0)!=".ps")
552     error, "pdf_finish only works with postscipt hcp files";
553   name = strpart(psname, 1:-3) + ".pdf";
554   gscmd = EPSGS_CMD+" -sDEVICE=pdfwrite -sOutputFile=\"%s\" \"%s\"";
555   system, swrite(format=gscmd, name, psname);
556   remove, psname;
557   return name;
558 }
559 
560 local png_dpi;
561 local png_gray;
562 local png_smooth;
563 /* DOCUMENT png_dpi, png_gray, png_smooth
564      You can set these variables to change the default values
565      of the dpi=, gray=, and smooth= keywords for the png command
566    SEE ALSO: png
567  */
568 
569 func png(name, dpi=, gray=, smooth=)
570 /* DOCUMENT png, name
571      writes the picture in the current graphics window to the PNG
572      file NAME+".png" (i.e.- the suffix .png is added to NAME).  The
573      png file is intended to be imported into MS PowerPoint or other
574      commercial presentation software.  This function starts ghostscript
575      using the EPSGS_CMD variable.  With the gray=1 keyword, you get
576      the pnggray ghostscript device, otherwise png16m.
577      The default yorick graphics window is 6 inches square, and by
578      default png produces 300 dpi (dot per inch) output.  You can change
579      this with the dpi= keyword; dpi=72 is screen resolution.
580      Finally, the smooth=1 keyword sets the TextAlphaBits and
581      GraphicsAlphaBits postscript variables to 2; smooth=2 sets them
582      to 4, which produce increasing levels of anti-aliasing.  With
583      smooth=1 or smooth=2, you can probably get away with lower dpi.
584      The default is smooth=0.  (Arguably, smooth=2 and dpi=72 or 100
585      should be the defaults.  But this can cause hairline artifacts in
586      plf or plfc output; see help,pdf.)
587      The default values of the keywords can be changed by setting
588      the corresponding extern variable png_dpi, png_gray, or png_smooth.
589    SEE ALSO: pdf, svg, jpeg, eps, hcps, window, plg, no_window
590  */
591 {
592   if (strpart(name, -3:0) == ".png") name = strpart(name,1:-4);
593   /* first run ghostscript to produce an eps translated to (0,0) */
594   psname = eps(name+".png", pdf=1);
595   /* second run ghostscript to produce the png */
596   gscmd = EPSGS_CMD+" -sDEVICE=%s %s -sOutputFile=\"%s\"%s \"%s\"";
597   dev = (gray || png_gray)? "pnggray" : "png16m";
598   if (is_void(dpi)) dpi = png_dpi? png_dpi : 300;
599   dpi = dpi? "-r"+print(dpi)(1) : "";
600   if (is_void(smooth)) smooth = png_smooth;
601   if (smooth) {
602     smooth = (smooth==1)? 2 : 4;
603     smooth = " "+swrite(format=GS_SMOOTH_OPT, smooth, smooth);
604   } else {
605     smooth = "";
606   }
607   system, swrite(format=gscmd, dev, dpi, name+".png", smooth, psname);
608   remove, psname;
609 }
610 
611 GS_SMOOTH_OPT = "-dTextAlphaBits=%ld -dGraphicsAlphaBits=%ld"
612 
613 func jpeg(name, dpi=, gray=)
614 /* DOCUMENT jpeg, name
615      writes the picture in the current graphics window to the JPEG
616      file NAME+".jpg" (i.e.- the suffix .jpg is added to NAME).  The
617      jpeg file is intended to be imported into MS PowerPoint or other
618      commercial presentation software.  This function starts ghostscript
619      using the EPSGS_CMD variable.  With the gray=1 keyword, you get
620      the jpeggray ghostscript device, otherwise jpeg.
621      The default yorick graphics window is 6 inches square, and by
622      default jpeg produces 72 dpi (dot per inch) output.  You can change
623      this with the dpi= keyword; dpi=300 is extremely high resolution.
624    SEE ALSO: svg, png, pdf, eps, hcps, window, plg, no_window
625  */
626 {
627   if (strpart(name, -3:0) == ".jpg") name = strpart(name,1:-4);
628   /* first run ghostscript to produce an eps translated to (0,0) */
629   psname = eps(name+".jpg", pdf=1);
630   /* second run ghostscript to produce the cropped pdf */
631   gscmd = EPSGS_CMD+" -sDEVICE=%s %s -sOutputFile=\"%s\" \"%s\"";
632   dev = gray? "jpeggray" : "jpeg";
633   dpi = dpi? "-r"+print(dpi)(1) : "";
634   system, swrite(format=gscmd, dev, dpi, name+".jpg", psname);
635   remove, psname;
636 }
637 
svg(name)638 func svg(name)
639 /* DOCUMENT svg, name
640      writes the picture in the current graphics window to the SVG
641      file NAME+".svg" (i.e.- the suffix .svg is added to NAME).  The
642      svg file can be inserted into html and interpreted by most Web
643      browsers.  This function starts ghostscript using the EPSGS_CMD
644      variable.
645 
646      You may have problems with hairline artifacts in plf or plfc output
647      (they also show up occasionally in pdf or postscript output).
648      This turns out to be caused by anti-aliasing (for pdf or ps as well);
649      the files are correct, but modern rendering engines create the
650      artifacts by trying to soften pixelated edges.
651 
652      In SVG, the solution is to set the shape-rendering property to
653      shape-rendering='crispEdges' or shape-rendering='optimizeSpeed'
654      which can be done either globally in the leading <svg> tag, or
655      in each group <g> tag ghostscript uses to represent a filled polygon.
656      I don't know how to make ghostscript do that for you.  Oddly
657      enough, shapeRendering='geometricPrecision" apparently means
658      anti-aliasing is turned on; the fuzzy edges causes the hairlines
659      you see, since each polygon fuzzes its own edges without paying
660      any attention to the adjacent polygon's color.
661    SEE ALSO: png, pdf, jpeg, eps, hcps, window, plg, no_window
662  */
663 {
664   if (strpart(name, -3:0) == ".svg") name = strpart(name,1:-4);
665   /* first run ghostscript to produce an eps translated to (0,0) */
666   svgname = eps(name+".svg", pdf=1);
667   /* second run ghostscript to produce the svg */
668   gscmd = EPSGS_CMD+" -sDEVICE=%s %s -sOutputFile=\"%s\" \"%s\"";
669   dev = "svg";
670   opt = "";
671   system, swrite(format=gscmd, dev, opt, name+".svg", svgname);
672   remove, svgname;
673 }
674 
675 extern fma;
676 /* DOCUMENT fma
677      frame advance the current graphics window.  The current picture
678      remains displayed in the associated X window until the next element
679      is actually plotted.
680    SEE ALSO: window, hcp, animate, plg, no_window
681  */
682 
683 extern hcp;
684 extern hcpon;
685 extern hcpoff;
686 /* DOCUMENT hcp
687             hcpon
688             hcpoff
689      The hcp command sends the picture displayed in the current graphics
690      window to the hardcopy file.  (The name of the default hardcopy file
691      can be specified using hcp_file; each individual graphics window may
692      have its own hardcopy file as specified by the window command.)
693      The hcpon command causes every fma (frame advance) command to do
694      and implicit hcp, so that every frame is sent to the hardcopy file.
695      The hcpoff command reverts to the default "demand only" mode.
696    SEE ALSO: window, fma, plg, pdf, eps, hcps, no_window
697  */
698 
699 extern redraw;
700 /* DOCUMENT redraw
701      redraws the X window associated with the current graphics window.
702    SEE ALSO: window, fma, hcp, plg
703  */
704 
705 extern palette;
706 /* DOCUMENT palette, filename
707          or palette, source_window_number
708          or palette, red, green, blue, ntsc=1/0
709          or palette, red, green, blue, gray
710          or palette, red, green, blue, query=1
711          or palette, red, green, blue, gray, query=1
712      sets (or retrieves with query=1) the palette for the current
713      graphics window.
714 
715      The cmap function provides a higher level interface, including
716      dozens more named palette choices.
717 
718      The FILENAME is the name of a Gist palette file; the standard
719      palettes are "earth.gp", "stern.gp", "rainbow.gp", "heat.gp",
720      "gray.gp", and "yarg.gp".  Use the maxcolors keyword in the
721      pldefault command to put an upper limit on the number of
722      colors which will be read from the palette in FILENAME.
723 
724      In the second form, the palette for the current window is copied
725      from the SOURCE_WINDOW_NUMBER.  If the X colormap for the window is
726      private, there will still be two separate X colormaps for the two
727      windows, but they will have the same color values.
728 
729      In the third form, RED, GREEN, and BLUE are 1-D arrays of the same
730      length specifying the palette you wish to install; the values
731      should vary between 0 and 255, and your palette should have no
732      more than 240 colors.  If ntsc=0, monochrome devices (such as most
733      laser printers) will use the average brightness to translate your
734      colors into gray; otherwise, the NTSC (television) averaging will
735      be used (.30*RED+.59*GREEN+.11*BLUE).  Alternatively, you can specify
736      GRAY explicitly.
737 
738      Ordinarily, the palette is not dumped to a hardcopy file
739      (color hardcopy is still rare and expensive), but you can
740      force the palette to dump using the window or hcp_file commands.
741 
742      See the dump= keyword for the hcp_file and window commands if you
743      are having trouble getting color in your hardcopy files.
744 
745    SEE ALSO: cmap, window, fma, hcp, pldefault, plg
746  */
747 
748 extern animate;
749 /* DOCUMENT animate
750          or animate, 0/1
751      without any arguments, toggles animation mode; with argument 0,
752      turns off animation mode, with argument 1 turns on animation mode.
753      In animation mode, the X window associated with a graphics window
754      is actually an offscreen pixmap which is bit-blitted onscreen
755      when an fma command is issued.  This is confusing unless you are
756      actually trying to make a movie, but results in smoother animation
757      if you are.  Generally, you should turn animation on, run your movie,
758      then turn it off.
759    SEE ALSO: window, fma, plg
760  */
761 
762 extern plsys;
763 /* DOCUMENT plsys, n
764          or plsys(n)   or   plsys()
765      sets the current coordinate system to number N in the current
766      graphics window.  If N equals 0, subsequent elements will be
767      plotted in absolute NDC coordinates outside of any coordinate
768      system.  The default style sheet "work.gs" defines only a single
769      coordinate system, so the only other choice is N equal 1.  You
770      can make up your own style sheet (using a text editor) which
771      defines mulitple coordinate systems.  You need to do this if
772      you want to display four plots side by side on a single page,
773      for example.  The standard style sheets "work2.gs" and "boxed2.gs"
774      define two overlayed coordinate systems with the first labeled
775      to the right of the plot and the second labeled to the left of
776      the plot.  When using overlayed coordinate systems, it is your
777      responsibility to ensure that the x-axis limits in the two
778      systems are identical.
779      Return value is coordinate system setting before this call;
780      input n may be nil to retrieve this without changing it.  Return
781      value can be <0 if the information is unavailable for some reason.
782    SEE ALSO: window, limits, plg
783  */
784 
785 /*= SECTION(plotter) plotting functions ====================================*/
786 
787 extern plg;
788 /* DOCUMENT plg, y, x
789          or plg, y
790      plots a graph of Y versus X.  Y and X must be 1-D arrays of equal
791      length; if X is omitted, it defaults to [1, 2, ..., numberof(Y)].
792      A keyword n=[n1,n2,n3,...nN] can be used to add N curves.  In this
793      case, sum(n) must be numberof(y).
794      The following keywords are legal (each has a separate help entry):
795    KEYWORDS: legend, hide
796              type, width, color, closed, smooth
797              marks, marker, mspace, mphase
798              rays, arrowl, arroww, rspace, rphase
799    SEE ALSO: plg, plm, plc, plv, plf, pli, plt, pldj, plfp, plmk
800              limits, logxy, range, fma, hcp
801  */
802 
803 extern plm;
804 /* DOCUMENT plm, y, x, boundary=0/1, inhibit=0/1/2
805          or plm, y, x, ireg, boundary=0/1, inhibit=0/1/2
806          or plm, boundary=0/1, inhibit=0/1/2
807      plots a mesh of Y versus X.  Y and X must be 2-D arrays with equal
808      dimensions.  If present, IREG must be a 2-D region number array
809      for the mesh, with the same dimensions as X and Y.  The values of
810      IREG should be positive region numbers, and zero for zones which do
811      not exist.  The first row and column of IREG never correspond to any
812      zone, and should always be zero.  The default IREG is 1 everywhere
813      else.  If present, the BOUNDARY keyword determines whether the
814      entire mesh is to be plotted (boundary=0, the default), or just the
815      boundary of the selected region (boundary=1).  If present, the
816      INHIBIT keyword causes the (X(,j),Y(,j)) lines to not be plotted
817      (inhibit=1), or the (X(i,),Y(i,)) lines to not be plotted (inhibit=2).
818      By default (inhibit=0), mesh lines in both logical directions are
819      plotted.
820      The Y, X, and IREG arguments may all be omitted to default to the
821      mesh set by the most recent plmesh call.
822      The following keywords are legal (each has a separate help entry):
823    KEYWORDS: legend, hide
824              type, width, color
825              region
826    SEE ALSO: plg, plm, plc, plv, plf, pli, plt, pldj, plfp, plmesh
827              limits, logxy, range, fma, hcp
828  */
829 
830 extern plmesh;
831 /* DOCUMENT plmesh, y, x, ireg, triangle=tri_array
832          or plmesh
833      sets the default mesh for subsequent plm, plc, plv, and plf calls.
834      In the second form, deletes the default mesh (until you do this,
835      or switch to a new default mesh, the default mesh arrays persist and
836      take up space in memory).  The Y, X, and IREG arrays should all be
837      the same shape; Y and X will be converted to double, and IREG will
838      be converted to int.  If IREG is omitted, it defaults to IREG(1,)=
839      IREG(,1)= 0, IREG(2:,2:)=1; that is, region number 1 is the whole
840      mesh.  The triangulation array TRI_ARRAY is used by plc; the
841      correspondence between TRI_ARRAY indices and zone indices is the
842      same as for IREG, and its default value is all zero.
843      The IREG or TRI_ARRAY arguments may be supplied without Y and X
844      to change the region numbering or triangulation for a given set of
845      mesh coordinates.  However, a default Y and X must already have been
846      defined if you do this.
847      If Y is supplied, X must be supplied, and vice-versa.
848    SEE ALSO: plm, plc, plv, plf, plfp
849  */
850 
851 extern plc;
852 /* DOCUMENT plc, z, y, x, levs=z_values
853          or plc, z, y, x, ireg, levs=z_values
854          or plc, z, levs=z_values
855      plots a contours of Z on the mesh Y versus X.  Y, X, and IREG are
856      as for plm.  The Z array must have the same shape as Y and X.
857      The function being contoured takes the value Z at each point
858      (X,Y) -- that is, the Z array is presumed to be point-centered.
859      The Y, X, and IREG arguments may all be omitted to default to the
860      mesh set by the most recent plmesh call.
861      The LEVS keyword is a list of the values of Z at which you want
862      contour curves.  The default is eight contours spanning the
863      range of Z.
864      See plfc if you want to color the regions between contours.
865      The following keywords are legal (each has a separate help entry):
866    KEYWORDS: legend, hide
867              type, width, color, smooth
868              marks, marker, mspace, mphase
869              smooth, triangle, region
870    SEE ALSO: plg, plm, plc, plv, plf, pli, plt, pldj, plfp, plmesh, plfc
871              contour, spann, limits, logxy, range, fma, hcp
872  */
873 
874 extern plv;
875 /* DOCUMENT plv, vy, vx, y, x, scale=dt
876          or plv, vy, vx, y, x, ireg, scale=dt
877          or plv, vy, vx, scale=dt
878      plots a vector field (VX,VY) on the mesh (X,Y).  Y, X, and IREG are
879      as for plm.  The VY and VX arrays must have the same shape as Y and X.
880      The Y, X, and IREG arguments may all be omitted to default to the
881      mesh set by the most recent plmesh call.
882      The SCALE keyword is the conversion factor from the units of
883      (VX,VY) to the units of (X,Y) -- a time interval if (VX,VY) is a velocity
884      and (X,Y) is a position -- which determines the length of the
885      vector "darts" plotted at the (X,Y) points.  If omitted, SCALE is
886      chosen so that the longest ray arrows have a length comparable
887      to a "typical" zone size.
888      You can use the scalem keyword in pledit to make adjustments to the
889      SCALE factor computed by default.
890      The following keywords are legal (each has a separate help entry):
891    KEYWORDS: legend, hide
892              type, width, color, smooth
893              marks, marker, mspace, mphase
894              triangle, region
895    SEE ALSO: plg, plm, plc, plv, plf, pli, plt, pldj, plfp, plmesh, pledit,
896              limits, logxy, range, fma, hcp
897  */
898 
899 extern plf;
900 /* DOCUMENT plf, z, y, x
901          or plf, z, y, x, ireg
902          or plf, z
903      plots a filled mesh Y versus X.  Y, X, and IREG are as for plm.
904      The Z array must have the same shape as Y and X, or one smaller
905      in both dimensions.  If Z is of type char, it is used "as is",
906      otherwise it is linearly scaled to fill the current palette, as
907      with the bytscl function.
908      (See the bytscl function for explanation of top, cmin, cmax.)
909      The mesh is drawn with each zone in the color derived from the Z
910      function and the current palette; thus Z is interpreted as a
911      zone-centered array.
912 
913      As for pli and plfp, Z may also be a 3x(NX-1)x(NY-1) array
914      of char giving the [r,g,b] components of each color.  See the
915      color keyword for cautions about using this if you do not have
916      a true color display.
917 
918      The Y, X, and IREG arguments may all be omitted to default to the
919      mesh set by the most recent plmesh call.
920      A solid edge can optionally be drawn around each zone by setting
921      the EDGES keyword non-zero.  ECOLOR and EWIDTH determine the edge
922      color and width.  The mesh is drawn zone by zone in order from
923      IREG(2+imax) to IREG(jmax*imax) (the latter is IREG(imax,jmax)),
924      so you can achieve 3D effects by arranging for this order to
925      coincide with back-to-front order.  If Z is nil, the mesh zones
926      are filled with the background color, which you can use to
927      produce 3D wire frames.
928      The following keywords are legal (each has a separate help entry):
929    KEYWORDS: legend, hide
930              region, top, cmin, cmax, edges, ecolor, ewidth
931    SEE ALSO: plg, plm, plc, plv, plf, pli, plt, pldj, plfp, plmesh,
932              limits, logxy, range, fma, hcp, palette, bytscl, histeq_scale
933  */
934 
935 extern plfp;
936 /* DOCUMENT plfp, z, y, x, n
937      plots a list of filled polygons Y versus X, with colors Z.
938      The N array is a 1D list of lengths (number of corners) of the
939      polygons; the 1D colors array Z has the same length as N.  The
940      X and Y arrays have length sum(N).
941      If Z is of type char, it is used "as is", otherwise it is linearly
942      scaled to fill the current palette, as with the bytscl function.
943      If Z is nil, the background color is used for every polygon.
944      (See the bytscl function for explanation of top, cmin, cmax.)
945 
946      As for plf and pli, Z may also be a 3-by-numberof(N) array of
947      char giving the [r,g,b] components of each color.  See the
948      color keyword for cautions about using this if you do not have
949      a true color display.
950 
951      As a special case, if n(2:)==1, the first polygon is assumed
952      to have NDC coordinates, while the remaining individual X and Y
953      values are in world coordinates.  The first polygon is drawn
954      numberof(n)-1 times, with its (0,0) placed at each of the
955      individual (X,Y) values in succession.  This is a hack to enable
956      plotting of more elaborate data markers than plg,type=0 -- see
957      the plmk function for details.
958 
959      The following keywords are legal (each has a separate help entry):
960    KEYWORDS: legend, hide, top, cmin, cmax, edges, ecolor, ewidth
961    SEE ALSO: plg, plm, plc, plv, plf, pli, plt, pldj, plfc
962              limits, logxy, range, fma, hcp
963  */
964 
965 extern pli;
966 /* DOCUMENT pli, z
967          or pli, z, x1, y1
968          or pli, z, x0, y0, x1, y1
969      plots the image Z as a cell array -- an array of equal rectangular
970      cells colored according to the 2-D array Z.  The first dimension
971      of Z is plotted along x, the second dimension is along y.
972      If Z is of type char, it is used "as is", otherwise it is linearly
973      scaled to fill the current palette, as with the bytscl function.
974      (See the bytscl function for explanation of top, cmin, cmax.)
975 
976      As for plf and plfp, Z may also be a 3D array with 1st dimension 3
977      of char giving the [r,g,b] components of each color.  See the
978      color keyword for cautions about using this if you do not have
979      a true color display.
980 
981      If X1 and Y1 are given, they represent the coordinates of the
982      upper right corner of the image.  If X0, and Y0 are given, they
983      represent the coordinates of the lower left corner, which is at
984      (0,0) by default.  If only the Z array is given, each cell will be
985      a 1x1 unit square, with the lower left corner of the image at (0,0).
986      The following keywords are legal (each has a separate help entry):
987    KEYWORDS: legend, hide, top, cmin, cmax
988    SEE ALSO: plg, plm, plc, plv, plf, pli, plt, pldj, plfp,
989              limits, logxy, range, fma, hcp, palette, bytscl, histeq_scale
990  */
991 
992 extern pldj;
993 /* DOCUMENT pldj, x0, y0, x1, y1
994      plots disjoint lines from (X0,Y0) to (X1,Y1).  X0, Y0, X1, and Y1
995      may have any dimensionality, but all must have the same number of
996      elements.
997      The following keywords are legal (each has a separate help entry):
998    KEYWORDS: legend, hide
999              type, width, color
1000    SEE ALSO: plg, plm, plc, plv, plf, pli, plt, pldj, plfp
1001              limits, logxy, range, fma, hcp
1002  */
1003 
1004 extern plt;
1005 /* DOCUMENT plt, text, x, y, tosys=0/1
1006      plots TEXT (a string) at the point (X,Y).  The exact relationship
1007      between the point (X,Y) and the TEXT is determined by the
1008      justify keyword.  TEXT may contain newline ("\n") characters
1009      to output multiple lines of text with a single call.  The
1010      coordinates (X,Y) are NDC coordinates (outside of any coordinate
1011      system) unless the tosys keyword is present and non-zero, in
1012      which case the TEXT will be placed in the current coordinate
1013      system.  However, the character height is NEVER affected by the
1014      scale of the coordinate system to which the text belongs.
1015      Note that the pledit command takes dx and/or dy keywords to
1016      adjust the position of existing text elements.
1017 
1018      The characters ^, _, and ! are treated specially in TEXT.
1019      ^ begins a superscript, _ begins a subscript, and ! causes the
1020      following character to be rendered using the symbol font.  As
1021      special cases, !^, !_, and !! render the ^, _, and ! characters
1022      themselves.  However, if ! is the final character of TEXT
1023      (or immediately before a newline in multiline text), it
1024      loses its special meaning.  TEXT has just three modes: ordinary,
1025      superscript, and subscript.  A ^ character enters superscript
1026      mode from ordinary or subscript mode, and returns to ordinary
1027      mode from superscript mode.  A _ enters subscript mode, except
1028      from subscript mode it returns to ordinary mode.  For example,
1029      Euclid said, "!pr^2", and Einstein said, "G_!s!n_=8!pT_!s!n".
1030      One final special escape: !] produces the ^ character in the
1031      symbol font (it is a perpendicular sign, whereas ] is just ]).
1032 
1033      The following keywords are legal (each has a separate help entry):
1034    KEYWORDS: legend, hide
1035              color, font, height, opaque, orient, justify
1036    SEE ALSO: plt1, plg, plm, plc, plv, plf, pli, plt, pldj, plfp, pledit
1037              limits, range, fma, hcp, pltitle
1038  */
1039 
1040 func plt1(text, x, y, tosys=, color=,font=,height=,opaque=,orient=,justify=)
1041 /* DOCUMENT plt1, text, x, y
1042      same as plt, but TEXT, X, and Y may be arrays to plot multiple
1043      strings.  The tosys= keyword works as for plt.
1044    KEYWORDS: color, font, height, opaque, orient, justify
1045    SEE ALSO: plt
1046  */
1047 {
1048   n= array(0.,dimsof(text,x,y));
1049   x+= n;
1050   y+= n;
1051   text+= array(string,dimsof(n));
1052   n= numberof(n);
1053   for (i=1 ; i<=n ; ++i)
1054     plt,text(i),x(i),y(i),tosys=tosys,color=color,font=font,height=height,
1055       opaque=opaque,orient=orient,justify=justify;
1056 }
1057 
pltitle(title)1058 func pltitle(title)
1059 /* DOCUMENT pltitle, title
1060      Plot TITLE centered above the coordinate system for any of the
1061      standard Gist styles.  You may want to customize this for other
1062      plot styles.
1063      The external variables pltitle_height, pltitle_font, pltitle_xadj,
1064      and pltitle_yadj determine the font and position of the title,
1065      if you want to change those.
1066    SEE ALSO: plt, xytitles
1067  */
1068 {
1069   port = viewport();
1070   x = port(zcen:1:2)(1) + pltitle_xadj;
1071   y = port(4) + pltitle_yadj;
1072   plt, title, x, y, font=pltitle_font, justify="CB", height=pltitle_height;
1073 }
1074 
xytitles(xtitle,ytitle,adjust)1075 func xytitles(xtitle, ytitle, adjust)
1076 /* DOCUMENT xytitles, xtitle, ytitle
1077          or xytitles, xtitle, ytitle, [deltax,deltay]
1078      Plot XTITLE horizontally under the viewport and YTITLE vertically
1079      to the left of the viewport.  If the tick numbers interfere with
1080      the labels, you can specify the [DELTAX,DELTAY] in NDC units to
1081      displace the labels.  (Especially for the y title, the adjustment
1082      may depend on how many digits the numbers on your scale actually
1083      have.)  Note that DELTAX moves YTITLE and DELTAY moves XTITLE.
1084      The external variables pltitle_height, pltitle_font, xtitle_xadj,
1085      xtitle_yadj, ytitle_xadj, and ytitle_yadj determine the font and
1086      unadjusted position of the titles, if you want to change those.
1087      WARNING: There is no easy way to ensure that this type of title
1088               will not interfere with the tick numbering.  Interference
1089               may make the numbers or the title or both illegible.
1090    SEE ALSO: plt, pltitle
1091  */
1092 {
1093   if (is_void(adjust)) adjust = [0., 0.];
1094   port = viewport();
1095   x = port(zcen:1:2)(1) + xtitle_xadj;
1096   y = port(3) + xtitle_yadj + adjust(2);
1097   if (xtitle && strlen(xtitle))
1098     plt, xtitle, x, y, font=pltitle_font, justify="CT", height=pltitle_height;
1099   x = port(1) + ytitle_xadj + adjust(1);
1100   y = port(zcen:3:4)(1) + ytitle_yadj;
1101   if (ytitle && strlen(ytitle))
1102     plt, ytitle, x, y,
1103       font=pltitle_font, justify="CB", height=pltitle_height, orient=1;
1104 }
1105 
1106 pltitle_height= 18;
1107 pltitle_font= "helvetica";
1108 /* default title center locations relative to midpoint of viewport edge */
1109 pltitle_xadj = 0.;
1110 pltitle_yadj = 0.02;
1111 xtitle_xadj = 0.;
1112 xtitle_yadj = -0.05;
1113 ytitle_xadj = -0.05;
1114 ytitle_yadj = 0.;
1115 
1116 /*= SECTION(plotlim) plot limits and axis scaling ==========================*/
1117 
1118 e= "e";         /* for use with limits and range functions */
1119 
1120 extern limits;
1121 /* DOCUMENT limits
1122          or limits, xmin, xmax, ymin, ymax,
1123                     square=0/1, nice=0/1, restrict=0/1
1124          or old_limits= limits()
1125          or limits, old_limits
1126 
1127      In the first form, restores all four plot limits to extreme values.
1128 
1129      In the second form, sets the plot limits in the current coordinate
1130      system to XMIN, XMAX, YMIN, YMAX, which may be nil or omitted to
1131      leave the corresponding limit unchanged, a number to fix the
1132      corresponding limit to a specified value, or the string "e" to
1133      make the corresponding limit take on the extreme value of the
1134      currently displayed data.
1135 
1136      If present, the square keyword determines whether limits marked
1137      as extreme values will be adjusted to force the x and y scales
1138      to be equal (square=1) or not (square=0, the default).
1139      If present, the nice keyword determines whether limits will be
1140      adjusted to nice values (nice=1) or not (nice=0, the default).
1141      There is a subtlety in the meaning of "extreme value" when one
1142      or both of the limits on the OPPOSITE axis have fixed values --
1143      does the "extreme value" of the data include points which
1144      will not be plotted because their other coordinate lies outside
1145      the fixed limit on the opposite axis (restrict=0, the default),
1146      or not (restrict=1)?
1147 
1148      If called as a function, limits returns an array of 5 doubles;
1149      OLD_LIMITS(1:4) are the current xmin, xmax, ymin, and ymax,
1150      and int(OLD_LIMITS(5)) is a set of flags indicating extreme
1151      values and the square, nice, restrict, and log flags.
1152 
1153      In the fourth form, OLD_LIMITS is as returned by a previous
1154      limits call, to restore the limits to a previous state.
1155 
1156      In an X window, the limits may also be adjusted interactively
1157      with the mouse.  Drag left to zoom in and pan (click left to zoom
1158      in on a point without moving it), drag middle to pan, and click
1159      (and drag) right to zoom out (and pan).  If you click just above
1160      or below the plot, these operations will be restricted to the
1161      x-axis; if you click just to the left or right, the operations
1162      are restricted to the y-axis.  A ctrl-left click, drag, and
1163      release will expand the box you dragged over to fill the plot
1164      (other popular software zooms with this paradigm).  If the
1165      rubber band box is not visible with ctrl-left zooming, try
1166      ctrl-middle or ctrl-right for alternate XOR masks.  Such
1167      mouse-set limits are equivalent to a limits command specifying
1168      all four limits EXCEPT that the unzoom command can revert to
1169      the limits before a series of mouse zooms and pans.
1170 
1171      Holding the shift key and pressing the left mouse button is
1172      equivalent to pressing the middle mouse button.  Similarly,
1173      pressing meta-left is equivalent to the right button.  This
1174      permits access to the middle and right button functions on
1175      machines (e.g.- most laptops) with two button or one button
1176      mice.
1177 
1178      The limits you set using the limits or range functions carry over
1179      to the next plot -- that is, an fma operation does NOT reset the
1180      limits to extreme values.
1181 
1182    SEE ALSO: plsys, range, logxy, zoom_factor, unzoom, plg, viewport
1183  */
1184 
range(ymin,ymax)1185 func range(ymin, ymax) { limits,,, ymin, ymax; }
1186 /* DOCUMENT range, ymin, ymax
1187      sets the y-axis plot limits in the current coordinate system to
1188      YMIN, YMAX, which may be nil or omitted to leave the corresponding
1189      limit unchanged, a number to fix the corresponding limit to a
1190      specified value, or the string "e" to make the corresponding limit
1191      take on the extreme value of the currently displayed data.
1192      Use    limits, xmin, xmin
1193      to accomplish the same function for the x-axis plot limits.
1194    SEE ALSO: plsys, limits, logxy, plg
1195  */
1196 
1197 extern logxy;
1198 /* DOCUMENT logxy, xflag, yflag
1199      sets the linear/log axis scaling flags for the current coordinate
1200      system.  XFLAG and YFLAG may be nil or omitted to leave the
1201      corresponding axis scaling unchanged, 0 to select linear scaling,
1202      or 1 to select log scaling.
1203    SEE ALSO: plsys, limits, range, plg, gridxy
1204  */
1205 
1206 extern gridxy;
1207 /* DOCUMENT gridxy, flag
1208          or gridxy, xflag, yflag
1209      Turns on or off grid lines according to FLAG.  In the first form, both
1210      the x and y axes are affected.  In the second form, XFLAG and YFLAG
1211      may differ to have different grid options for the two axes.  In either
1212      case, a FLAG value of 0 means no grid lines (the default), a value of
1213      1 means grid lines at all major ticks (the level of ticks which get
1214      grid lines can be set in the style sheet), and a FLAG value of 2 means
1215      that the coordinate origin only will get a grid line.  In styles with
1216      multiple coordinate systems, only the current coordinate system is
1217      affected.
1218      The keywords can be used to affect the style of the grid lines.
1219 
1220      You can also turn the ticks off entirely.  (You might want to do this
1221      to plot your own custom set of tick marks when the automatic tick
1222      generating machinery will never give the ticks you want.  For example
1223      a latitude axis in degrees might reasonably be labeled "0, 30, 60,
1224      90", but the automatic machinery considers 3 an "ugly" number - only
1225      1, 2, and 5 are "pretty" - and cannot make the required scale.  In
1226      this case, you can turn off the automatic ticks and labels, and use
1227      plsys, pldj, and plt to generate your own.)
1228      To fiddle with the tick flags in this general manner, set the
1229      0x200 bit of FLAG (or XFLAG or YFLAG), and "or-in" the 0x1ff bits
1230      however you wish.  The meaning of the various flags is described
1231      in the file Y_SITE/gist/work.gs.  Additionally, you can use the
1232      0x400 bit to turn on or off the frame drawn around the viewport.
1233      Here are some examples:
1234         gridxy,0x233        work.gs default setting
1235         gridxy,,0x200       like work.gs, but no y-axis ticks or labels
1236         gridxy,,0x231       like work.gs, but no y-axis ticks on right
1237         gridxy,0x62b        boxed.gs default setting
1238 
1239      The three keywords base60=, degrees=, and hhmm= can be used to get
1240      alternative tick intervals for base 60 systems instead of the
1241      usual base 10 systems.  The keyword values are 0 to restore the
1242      default behavior, 1 to set the feature for the x axis, 2 to set it
1243      for the y axis, and 3 to set it for both axes.  The base60 feature
1244      allows ticks and labels at multiples of 30 (up to +-3600).  The
1245      degrees feature causes labels to be printed modulo 360 (so that a
1246      scale which runs from, say, 90 to 270 will be printed as 90 to 180
1247      then -180 to -90, mostly for longitude scales).  The hhmm feature
1248      causes labels to be printed in the form hh:mm (so that, for example,
1249      150 will be printed as 02:30, mostly for time of day scales).
1250 
1251    KEYWORDS: color, type, width, base60, degrees, hhmm
1252    SEE ALSO: window, plsys, limits, range, logxy, viewport
1253  */
1254 
1255 extern zoom_factor;
1256 /* DOCUMENT zoom_factor, factor
1257      sets the zoom factor for mouse-click zoom in and zoom out operations.
1258      The default FACTOR is 1.5; FACTOR should always be greater than 1.0.
1259    SEE ALSO: limits, range, unzoom, plg
1260  */
1261 
1262 extern unzoom;
1263 /* DOCUMENT unzoom
1264      restores limits to their values before zoom and pan operations
1265      performed interactively using the mouse.
1266      Use    old_limits=  limits()
1267             ...
1268             limits, old_limits
1269      to save and restore plot limits generally.
1270    SEE ALSO: limits, range, zoom_factor, plg
1271  */
1272 
1273 /*= SECTION(plotkey) keywords for plotting functions =======================*/
1274 
1275 local legend;
1276 /* DOCUMENT legend=   plotting keyword
1277      sets the legend for a plot.  The default legend is a concatentation
1278      of the strings used in the original plotting command (plg, plm, etc.),
1279      except for the plt command, which has no default legend.
1280      Legends are never plotted to the X window; use the plq command to
1281      see them interactively.  Legends will appear in hardcopy output
1282      unless they have been explicitly turned off.
1283    PLOTTING COMMANDS: plg, plm, plc, plv, plf, pli, plt, pldj
1284    SEE ALSO: hide
1285  */
1286 
1287 local hide;
1288 /* DOCUMENT hide=   plotting keyword
1289      sets the visibility of a plotted element.  The default is hide=0,
1290      which means that the element will be visible.  Use hide=1 to remove
1291      the element from the plot (but not from the display list).
1292    PLOTTING COMMANDS: plg, plm, plc, plv, plf, pli, plt, pldj
1293    SEE ALSO: legend
1294  */
1295 
1296 local type;
1297 /* DOCUMENT type=   plotting keyword
1298      selects line type.  Valid values are the strings "solid", "dash",
1299      "dot", "dashdot", "dashdotdot", and "none".  The "none" value
1300      causes the line to be plotted as a polymarker.  You should also
1301      check the plmk function if you need polymarkers.
1302      The type value may also be a number; 0 is "none", 1 is "solid",
1303      2 is "dash", 3 is "dot", 4 is "dashdot", and 5 is "dashdotdot".
1304    PLOTTING COMMANDS: plg, plm, plc, pldj
1305    SEE ALSO: width, color, marks, marker, rays, closed, smooth, plmk
1306  */
1307 
1308 local width;
1309 /* DOCUMENT width=   plotting keyword
1310      selects line width.  Valid values are positive floating point numbers
1311      giving the line thickness relative to the default line width of one
1312      half point, width= 1.0.
1313    PLOTTING COMMANDS: plg, plm, plc, pldj, plv (only if hollow=1)
1314    SEE ALSO: type, color, marks, marker, rays, closed, smooth
1315  */
1316 
1317 local color;
1318 /* DOCUMENT color=   plotting keyword
1319      selects line or text color.  Valid values are the strings "bg", "fg",
1320      "black", "white", "red", "green", "blue", "cyan", "magenta", "yellow",
1321      "grayd", "grayc", "grayb", graya", (grayd darkest, graya lightest)
1322      or a 0-origin index into the current palette.  The default is "fg".
1323      Negative numbers may be used instead of the strings: -1 is bg
1324      (background), -2 is fg (foreground), -3 is black, -4 is white,
1325      -5 is red, -6 is green, -7 is blue, -8 is cyan, -9 is magenta,
1326      -10 is yellow, -11 is grayd, -12 is grayc, -13 is grayb, and -14 is
1327      graya.  (The negative numbers are actually taken modulo
1328      256, so -1 is also 255, -2 is 254, and so on.)
1329 
1330      A color can also be a triple [r, g, b], with values running from
1331      0 for dark to 255 for full intensity.  Beware, however, of
1332      specifying an rgb color (either as a color keyword or to the
1333      plf, pli, or plfp commands) if your display is not a true color
1334      display (for example, if it is 8 bits deep or less).  In that
1335      case, it may switch to a 5x9x5 color cube, which causes a
1336      significant degradation in quality of rendering with smooth
1337      color palettes.  Furthermore, the hcp command will not work
1338      properly for rgb colors if the file is a CGM.  Use the rgb=1
1339      keyword in the window command to avoid having to re-issue a
1340      palette command after the first rgb object is drawn (this is
1341      unnecessary on true color screens).
1342 
1343      You can use color=torgb(name) to specify a W3C/X11 color.
1344 
1345    PLOTTING COMMANDS: plg, plm, plc, pldj, plt
1346    SEE ALSO: type, width, marks, marker, mcolor, rays, closed, smooth, torgb
1347  */
1348 
1349 local marks;
1350 /* DOCUMENT marks=   plotting keyword
1351      selects unadorned lines (marks=0), or lines with occasional markers
1352      (marks=1).  Ignored if type is "none" (indicating polymarkers instead
1353      of occasional markers).  The spacing and phase of the occasional
1354      markers can be altered using the mspace and mphase keywords; the
1355      character used to make the mark can be altered using the marker
1356      keyword.
1357    PLOTTING COMMANDS: plg, plc
1358    SEE ALSO: type, width, color, marker, rays, mspace, mphase, msize, mcolor
1359  */
1360 
1361 local marker;
1362 /* DOCUMENT marker=   plotting keyword
1363      selects the character used for occasional markers along a polyline,
1364      or for the polymarker if type is "none".  The special values
1365      '\1', '\2', '\3', '\4', and '\5' stand for point, plus, asterisk,
1366      circle, and cross, which are prettier than text characters on output
1367      to some devices.  The default marker is the next available capital
1368      letter, 'A', 'B', ..., 'Z'.
1369    PLOTTING COMMANDS: plg, plc
1370    SEE ALSO: type, width, color, marks, rays, mspace, mphase, msize, mcolor
1371  */
1372 
1373 local mspace, mphase, msize, mcolor;
1374 /* DOCUMENT mspace=   plotting keyword
1375          or mphase=   plotting keyword
1376          or msize=    plotting keyword
1377          or mcolor=   plotting keyword
1378      selects the spacing, phase, and size of occasional markers placed
1379      along polylines.  The msize also selects polymarker size if type
1380      is "none".  The spacing and phase are in NDC units (0.0013 NDC
1381      equals 1.0 point); the default mspace is 0.16, and the default
1382      mphase is 0.14, but mphase is automatically incremented for
1383      successive curves on a single plot.  The msize is in relative
1384      units, with the default msize of 1.0 representing 10 points.
1385      The mcolor keyword is the same as the color keyword, but controls
1386      the marker color instead of the line color.  Setting the color
1387      automatically sets the mcolor to the same value, so you only
1388      need to use mcolor if you want the markers for a curve to be a
1389      different color than the curve itself.
1390    PLOTTING COMMANDS: plg, plc
1391    SEE ALSO: type, width, color, marks, marker, rays
1392  */
1393 
1394 local rays;
1395 /* DOCUMENT rays=   plotting keyword
1396      selects unadorned lines (rays=0), or lines with occasional ray
1397      arrows (rays=1).  Ignored if type is "none".  The spacing and phase
1398      of the occasional arrows can be altered using the rspace and rphase
1399      keywords; the shape of the arrowhead can be modified using the
1400      arroww and arrowl keywords.
1401    PLOTTING COMMANDS: plg, plc
1402    SEE ALSO: type, width, color, marker, marks, rspace, rphase
1403              arroww, arrowl
1404  */
1405 
1406 local rspace, rphase, arroww, arrowl;
1407 /* DOCUMENT rspace=   plotting keyword
1408          or rphase=   plotting keyword
1409          or arroww=   plotting keyword
1410          or arrowl=   plotting keyword
1411      selects the spacing, phase, and size of occasional ray arrows
1412      placed along polylines.  The spacing and phase are in NDC units
1413      (0.0013 NDC equals 1.0 point); the default rspace is 0.13, and
1414      the default rphase is 0.11375, but rphase is automatically
1415      incremented for successive curves on a single plot.
1416      The arrowhead width, arroww, and arrowhead length, arrowl are
1417      in relative units, defaulting to 1.0, which translates to an
1418      arrowhead 10 points long and 4 points in half-width.
1419    PLOTTING COMMANDS: plg
1420    SEE ALSO: type, width, color, marks, marker, rays
1421  */
1422 
1423 local closed, smooth;
1424 /* DOCUMENT closed=   plotting keyword
1425          or smooth=   plotting keyword
1426      selects closed curves (closed=1) or default open curves (closed=0),
1427      or Bezier smoothing (smooth>0) or default piecewise linear curves
1428      (smooth=0).  The value of smooth can be 1, 2, 3, or 4 to get
1429      successively more smoothing.  Only the Bezier control points are
1430      plotted to an X window; the actual Bezier curves will show up in
1431      PostScript hardcopy files.  Closed curves join correctly, which
1432      becomes more noticeable for wide lines; non-solid closed curves
1433      may look bad because the dashing pattern may be incommensurate
1434      with the length of the curve.
1435    PLOTTING COMMANDS: plg, plc (smooth only)
1436    SEE ALSO: type, width, color, marks, marker, rays
1437  */
1438 
1439 local font, height, opaque, orient, justify;
1440 /* DOCUMENT font=     plotting keyword
1441          or height=   plotting keyword
1442          or opaque=   plotting keyword
1443          or orient=   plotting keyword
1444          or justify=  plotting keyword
1445      selects text properties.  The font can be any of the strings
1446      "courier", "times", "helvetica" (the default), "symbol", or
1447      "schoolbook".  Append "B" for boldface and "I" for italic, so
1448      "courierB" is boldface Courier, "timesI" is Times italic, and
1449      "helveticaBI" is bold italic (oblique) Helvetica.  Your X server
1450      should have the Adobe fonts (available free from the MIT X
1451      distribution tapes) for all these fonts, preferably at both 75
1452      and 100 dpi.  Occasionally, a PostScript printer will not be
1453      equipped for some fonts; often New Century Schoolbook is missing.
1454      The font keyword may also be an integer: 0 is Courier, 4 is Times,
1455      8 is Helvetica, 12 is Symbol, 16 is New Century Schoolbook, and
1456      you add 1 to get boldface and/or 2 to get italic (or oblique).
1457 
1458      The height is the font size in points; 14.0 is the default.
1459      X windows only has 8, 10, 12, 14, 18, and 24 point fonts, so
1460      don't stray from these sizes if you want what you see on the
1461      screen to be a reasonably close match to what will be printed.
1462 
1463      By default, opaque=0 and text is transparent.  Set opaque=1 to
1464      white-out a box before drawing the text.  The default orient
1465      (orient=0) is left-to-right text; set orient=1 for text rotated 90
1466      degrees so it reads upward, orient=2 for 180 degree rotation so
1467      it is upside down, and orient=3 for 270 degree rotation so it
1468      reads downward.
1469 
1470      The default text justification, justify="NN" is normal is both
1471      the horizontal and vertical directions.  Other possibilities
1472      are "L", "C", or "R" for the first character, meaning left,
1473      center, and right horizontal justification, and "T", "C", "H",
1474      "A", or "B", meaning top, capline, half, baseline, and bottom
1475      vertical justification.  The normal justification "NN" is equivalent
1476      to "LA".  Common values are "LA", "CA", and "RA" for garden variety
1477      left, center, and right justified text, with the y coordinate at the
1478      baseline of the last line in the string presented to plt.  The
1479      characters labeling the right axis of a plot are "RH", so that the
1480      y value of the text will match the y value of the corresponding
1481      tick.  Similarly, the characters labeling the bottom axis of a plot
1482      are "CT".  The justify= may also be a number, horizontal+vertical,
1483      where horizontal is 0 for "N", 1 for "L", 2 for "C", or 3 for "R",
1484      and vertical is 0 for "N", 4 for "T", 8 for "C", 12 for "H",
1485      16 for "A", or 20 for "B".
1486 
1487    PLOTTING COMMANDS: plt
1488    SEE ALSO: color
1489  */
1490 
1491 local region;
1492 /* DOCUMENT region=   plotting keyword
1493      selects the part of mesh to consider.  The region should match one
1494      of the numbers in the IREG array.  Putting region=0 (the default)
1495      means to plot the entire mesh, that is, everything EXCEPT region
1496      zero (non-existent zones).  Any other number means to plot only
1497      the specified region number; region=3 would plot region 3 only.
1498    PLOTTING COMMANDS: plm, plc, plv, plf
1499  */
1500 
1501 local triangle;
1502 /* DOCUMENT triangle=   plotting keyword
1503      sets the triangulation array for a contour plot.  The triangulation
1504      array must be the same shape as the IREG (region number) array, and
1505      the correspondence between mesh zones and indices is the same as
1506      for IREG.  The triangulation array is used to resolve the ambiguity
1507      in saddle zones, in which the function Z being contoured has two
1508      diagonally opposite corners high, and the other two corners low.
1509      The triangulation array element for a zone is 0 if the algorithm is
1510      to choose a triangulation, based on the curvature of the first
1511      contour to enter the zone.  If zone (i,j) is to be triangulated
1512      from point (i-1,j-1) to point (i,j), then TRIANGLE(i,j)=1,
1513      while if it is to be triangulated from (i-1,j) to (i,j-1), then
1514      TRIANGLE(i,j)=-1.  Contours will never cross this "triangulation
1515      line".
1516      You should rarely need to fiddle with the traingulation array;
1517      it is a hedge for dealing with pathological cases.
1518    PLOTTING COMMANDS: plc
1519  */
1520 
1521 local hollow, aspect;
1522 /* DOCUMENT hollow=   plotting keyword
1523          or aspect=   plotting keyword
1524      set the appearance of the "darts" of a vector field plot.  The
1525      default darts, hollow=0, are filled; use hollow=1 to get just the
1526      dart outlines.  The default is aspect=0.125; aspect is the ratio
1527      of the half-width to the length of the darts.  Use the color
1528      keyword to control the color of the darts.
1529    PLOTTING COMMANDS: plv
1530    SEE ALSO: color
1531  */
1532 
1533 local edges, ecolor, ewidth;
1534 /* DOCUMENT edges=   plotting keyword
1535          or ecolor=   plotting keyword
1536          or ewidth=   plotting keyword
1537      set the appearance of zone edges in a filled mesh plot (plf or plfp).
1538      By default, edges=0, and the zone edges are not plotted.  If
1539      edges=1, a solid line is drawn around each zone after it is
1540      filled; the edge color and width are given by ecolor and ewidth,
1541      which are "fg" and 1.0 by default.
1542    PLOTTING COMMANDS: plf
1543    SEE ALSO: color, width
1544  */
1545 
1546 /*= SECTION(plotq) plot query and edit functions ===========================*/
1547 
1548 extern plq;
1549 /* DOCUMENT plq
1550          or plq, n_element
1551          or plq, n_element, n_contour
1552          or legend_list= plq()
1553          or properties= plq(n_element, n_contour)
1554      Called as a subroutine, prints the list of legends for the current
1555      coordinate system (with an "(H)" to mark hidden elements), or prints
1556      a list of current properties of element N_ELEMENT (such as line type,
1557      width, font, etc.), or of contour number N_CONTOUR of element number
1558      N_ELEMENT (which must be contours generated using the plc command).
1559      Called as a function, returns either the list of legend strings, or a
1560      list of pointers to the values of the various element properties.
1561      Elements and contours are both numbered starting with one; hidden
1562      elements or contours are included in this numbering.
1563 
1564      The PROPERTIES list returned by plq is a list of pointers to the
1565      relevent properties for the specified graphical element.  Each
1566      possible property has a particular index in the returned PROPERTIES
1567      list as follows:
1568      *PROPERTIES(1)   int([element type (0 for none, 1 for plg, 2 for pldj,
1569                                          3 for plt, 4 for plm, 5 for plf,
1570                                          6 for plv, 7 for plc, 8 for pli,
1571                                          9 for plfp),
1572                            hide flag])
1573      *PROPERTIES(2)   string(legend)
1574      *PROPERTIES(3)   int array, depends on type (names match keywords):
1575        1 plg:  [color, type, marks, mcolor, marker, rays, closed, smooth]
1576        2 pldj: [color, type]
1577        3 plt:  [color, font, orient, justify, opaque]
1578        4 plm:  [color, type, region, boundary, inhibit]
1579        5 plf:  [region, edges, ecolor, rgb_flag]
1580        6 plv:  [region, color, hollow]
1581        7 plc:  [region, color, type, marks, mcolor, marker, smooth]
1582        8 pli:  [rgb_flag]
1583        9 plfp: [edges, ecolor, rgb_flag]
1584      *PROPERTIES(4)   double array, depends on type (names match keywords):
1585        1 plg:  [width, msize, mspace, mphase, rspace, rphase, arrowl, arroww]
1586        2 pldj: [width]
1587        3 plt:  [height, x, y]
1588        4 plm:  [width]
1589        5 plf:  [ewidth]
1590        6 plv:  [width, aspect, scale]
1591        7 plc:  [width, msize, mspace, mphase]
1592        8 pli:  [x0, y0, x1, y1]
1593        9 plfp: [ewidth]
1594      *PROPERTIES(5)   long array, depends on type (names match arguments):
1595        1 plg:  [npoints, &x, &y]
1596        2 pldj: [npoints, &x0, &y0, &x1, &y1]
1597        3 plt:  [nchars, &text]
1598        4 plm:  [imax, jmax, &x, &y, &ireg]
1599        5 plf:  [imax, jmax, &x, &y, &ireg, &colors]
1600        6 plv:  [imax, jmax, &x, &y, &ireg, &vx, &vy]
1601        7 plc:  [imax, jmax, &x, &y, &ireg, &z, &triangle, nlevs, &levs]
1602        8 pli:  [imax, jmax, &colors]
1603        9 plfp: [n, &x, &y, &colors, &pn]
1604      You can use the reshape function to peek at the data at the addresses
1605      returned in PROPERTIES(5) as longs.  The appropriate data types are:
1606      char for text, int for ireg, short for triangle, char for colors, and
1607      double for everything else.  In a plf, colors is (imax-1)-by-(jmax-1).
1608      Although PROPERTIES(5) returns pointers to the data plotted, attempting
1609      to poke new values into this data will not produce immediate changes
1610      to your plot, since the graphics package does not realize that anything
1611      has changed.  Use pledit to make changes to plotted elements.
1612 
1613      The plq function always operates on the current coordinate system
1614      in the current graphics window; use window and plsys to change these.
1615    SEE ALSO: window, plsys, pledit, pldefault, plg
1616  */
1617 
1618 extern pledit;
1619 /* DOCUMENT pledit, key1=value1, key2=value2, ...
1620          or pledit, n_element, key1=value1, key2=value2, ...
1621          or pledit, n_element, n_contour, key1=value1, key2=value2, ...
1622      changes some property of element number N_ELEMENT (and contour
1623      number N_CONTOUR of that element).  If N_ELEMENT and N_CONTOUR are
1624      omitted, the default is the most recently added element, or the
1625      element specified in the most recent plq query command.
1626 
1627      The keywords can be any of the keywords that apply to the current
1628      element.  These are:
1629        plg:  color, type, width,
1630              marks, mcolor, marker, msize, mspace, mphase,
1631              rays, rspace, rphase, arrowl, arroww,
1632              closed, smooth
1633        pldj: color, type, width
1634        plt:  color, font, height, orient, justify, opaque
1635        plm:  region, boundary, inhibit, color, type, width
1636        plf:  region
1637        plv:  region, color, hollow, width, aspect, scale
1638        plc:  region, color, type, width,
1639              marks, mcolor, marker, msize, mspace, mphase
1640              smooth, levs
1641      (For contours, if you aren't talking about a particular N_CONTOUR,
1642       any changes will affect ALL the contours.)
1643 
1644      A plv (vector field) element can also take the scalem
1645      keyword to multiply all vector lengths by a specified factor.
1646 
1647      A plt (text) element can also take the dx and/or dy
1648      keywords to adjust the text position by (dx,dy).
1649 
1650    SEE ALSO: window, plsys, plq, pldefault, plg
1651  */
1652 
1653 extern pldefault;
1654 /* DOCUMENT pldefault, key1=value1, key2=value2, ...
1655      sets default values for the various properties of graphical elements.
1656 
1657      The keywords can be most of the keywords that can be passed to the
1658      plotting commands:
1659        plg:  color, type, width,
1660              marks, mcolor, msize, mspace, mphase,
1661              rays, rspace, rphase, arrowl, arroww
1662        pldj: color, type, width
1663        plt:  color, font, height, orient, justify, opaque
1664        plm:  color, type, width
1665        plv:  color, hollow, width, aspect
1666        plc:  color, type, width,
1667              marks, mcolor, marker, msize, mspace, mphase
1668        plf:  edges, ecolor, ewidth
1669 
1670      The initial default values are:
1671        color="fg", type="solid", width=1.0 (1/2 point),
1672        marks=1, mcolor="fg", msize=1.0 (10 points),
1673           mspace=0.16, mphase=0.14,
1674        rays=0, arrowl=1.0 (10 points), arroww=1.0 (4 points),
1675           rspace=0.13, rphase=0.11375,
1676        font="helvetica", height=12.0, justify="NN", opaque=0,
1677        hollow= 0, aspect=0.125,
1678        edges=0, ecolor="fg", ewidth=1.0 (1/2 point)
1679 
1680      Additional default keywords are:
1681        dpi, style, legends  (see window command)
1682        palette              (to set default filename as in palette command)
1683        maxcolors            (default 200)
1684 
1685    SEE ALSO: window, plsys, plq, pledit, plg
1686  */
1687 
1688 /*= SECTION(plotmisc) miscellaneous plotting-related functions =============*/
1689 
1690 extern bytscl;
1691 /* DOCUMENT bytscl(z)
1692          or bytscl(z, top=max_byte, cmin=lower_cutoff, cmax=upper_cutoff)
1693      returns a char array of the same shape as Z, with values linearly
1694      scaled to the range 0 to one less than the current palette size.
1695      If MAX_BYTE is specified, the scaled values will run from 0 to
1696      MAX_BYTE instead.
1697      If LOWER_CUTOFF and/or UPPER_CUTOFF are specified, Z values outside
1698      this range are mapped to the cutoff value; otherwise the linear
1699      scaling maps the extreme values of Z to 0 and MAX_BYTE.
1700    SEE ALSO: plf, pli, histeq_scale
1701  */
1702 
1703 extern mesh_loc;
1704 /* DOCUMENT mesh_loc(y0, x0)
1705          or mesh_loc(y0, x0, y, x)
1706          or mesh_loc(y0, x0, y, x, ireg)
1707      returns the zone index (=i+imax*(j-1)) of the zone of the mesh
1708      (X,Y) (with optional region number array IREG) containing the
1709      point (X0,Y0).  If (X0,Y0) lies outside the mesh, returns 0.
1710      Thus, eg- ireg(mesh_loc(x0, y0, y, x, ireg)) is the region number of
1711      the region containing (x0,y0).  If no mesh specified, uses default.
1712      X0 and Y0 may be arrays as long as they are conformable.
1713 
1714      For mesh_loc wrappers to duplicate the functionality of the
1715      digitize and interp functions in 2D, see the library file digit2.i.
1716      Read help,digit2.
1717 
1718    SEE ALSO: plmesh, moush, mouse
1719  */
1720 
1721 extern contour;
1722 /* DOCUMENT nc= contour(yc,xc, level, z, y,x)
1723          or nc= contour(yc,xc, level, z, y,x,ireg)
1724 
1725      returns the points on the contour curve that would have been
1726      plotted by plc.  Z, Y, X, and IREG are as for plc, and the
1727      triangle= and region= keywords are accepted and have the same
1728      meaning as for plc.  Unlike plc, the triangle array is an output
1729      as well as an input to contour; if supplied it may be modified
1730      to reflect any triangulations which were performed by contour.
1731 
1732      LEVEL is a scalar z value to return the points at that contour
1733      level.  All such points lie on edges of the mesh.  If a contour
1734      curve closes, the final point is the same as the initial point
1735      (i.e.- that point is included twice in the returned list).
1736 
1737      LEVEL is a pair of z values [z0,z1] to return the points of
1738      a set of polygons which outline the regions between the two
1739      contour levels.  These will include points on the mesh boundary
1740      which lie between the levels, in addition to the edge points
1741      for both levels.  The polygons are closed, simply connected,
1742      and will not contain more than about 4000 points (larger polygons
1743      are split into pieces with a few points repeated where the pieces
1744      join).
1745 
1746      YC and XC are the output points on the curve(s), or nil if there
1747      are no points.  On input, they must be simple variable references,
1748      not expressions.  The return value NC is a list of the lengths of
1749      the polygons/polylines returned in (XC,YC), or nil if there are
1750      none.  numberof(XC)==numberof(YC)==sum(NC).  For the level pair
1751      case, YC, XC, and NC are ready to be used as inputs to plfp.
1752 
1753    KEYWORDS: triangle, region
1754    SEE ALSO: plc, plfp
1755  */
1756 
1757 extern mouse;
1758 /* DOCUMENT result= mouse(system, style, prompt)
1759      displays a PROMPT, then waits for a mouse button to be pressed,
1760      then released.  Returns array of eleven doubles:
1761        result= [x_pressed, y_pressed, x_released, y_released,
1762                 xndc_pressed, yndc_pressed, xndc_released, yndc_released,
1763                 system, button, modifiers]
1764 
1765      If SYSTEM>=0, the first four coordinate values will be relative to
1766      that coordinate system.
1767      For SYSTEM<0, the first four coordinate values will be relative to
1768      the coordinate system under the mouse when the button was pressed.
1769      The second four coordinates are always normalized device coordinates,
1770      which start at (0,0) in the lower left corner of the 8.5x11 sheet of
1771      paper the picture will be printed on, with 0.0013 NDC unit being
1772      1/72.27 inch (1.0 point).  Look in the style sheet for the location
1773      of the viewport in NDC coordinates (see the style keyword).
1774 
1775      If STYLE is 0, there will be no visual cues that the mouse
1776      command has been called; this is intended for a simple click.
1777      If STYLE is 1, a rubber band box will be drawn; if STYLE is 2,
1778      a rubber band line will be drawn.  These disappear when the
1779      button is released.
1780 
1781      Clicking a second button before releasing the first cancels the
1782      mouse function, which will then return nil.
1783      Ordinary text input also cancels the mouse function, which again
1784      returns nil.
1785 
1786      The left button reverses forground for background (by XOR) in
1787      order to draw the rubber band (if any).  The middle and right
1788      buttons use other masks, in case the rubber band is not visible
1789      with the left button.
1790 
1791      long(result(9)) is the coordinate system in which the first four
1792      coordinates are to be interpreted.
1793      long(result(10)) is the button which was pressed, 1 for left, 2
1794      for middle, and 3 for right (4 and 5 are also possible).
1795      long(result(11)) is a mask representing the modifier keys which
1796      were pressed during the operation: 1 for shift, 2 for shift lock,
1797      4 for control, 8 for mod1 (alt or meta), 16 for mod2, 32 for mod3,
1798      64 for mod4, and 128 for mod5.
1799 
1800      Holding the shift key and pressing the left mouse button is
1801      equivalent to pressing the middle mouse button.  Similarly,
1802      pressing meta-left is equivalent to the right button.  This
1803      permits access to the middle and right button functions on
1804      machines (e.g.- most laptops) with two button or one button
1805      mice.  The long(result(10)) value returned by mouse() reflects
1806      this convention, returning 2 or 3 for those cases, even though
1807      it is button 1 that is actually being pressed.  Therefore, there
1808      is no way to distinguish shift-left from shift-middle, because the
1809      long(result(11)) mask indicates tht the shift button is pressed
1810      in either case.  (And on a machine without a middle button,
1811      there would be no way to emulate shift-middle anyway.)
1812 
1813    SEE ALSO: moush
1814  */
1815 
moush(y,x,ireg)1816 func moush(y, x, ireg)
1817 /* DOCUMENT moush()
1818          or moush(y, x, ireg)
1819      returns the 1-origin zone index for the point clicked in
1820      for the default mesh, or for the mesh (X,Y) (region array IREG).
1821  */
1822 {
1823   xy= mouse(-1, 0, "<Click mouse in mesh>");
1824   if (is_void(xy)) return [];
1825   else return mesh_loc(xy(2), xy(1), y, x, ireg);
1826 }
1827 
1828 extern pause;
1829 /* DOCUMENT pause, milliseconds
1830          or pause(milliseconds)
1831      pause for the specified number of milliseconds of wall clock
1832      time, or until input arrives from the keyboard.
1833      If you call pause as a function, the return value is 1
1834      if the specified number of milliseconds elapsed, or 0 if
1835      keyboard input caused the pause to abort.
1836      This is intended for use in creating animated sequences.
1837  */
1838 
1839 extern rgb_read;
1840 /* DOCUMENT rgb = rgb_read()
1841          or rgb = rgb_read(n)
1842      Read contents of current graphics window, or of graphics window N.
1843      RGB is a 3xNXxNY array of char where NXxNY is the current shape of
1844      the window in pixels.  RGB(1,,) is the red component, RGB(2,,) is
1845      the green component, and RGB(3,,) is the blue component, with 0
1846      black and 255 full intensity.  RGB(,,1) is the top row of the
1847      window, RGB(,,2) the second row, and so on to RGB(,,0), which is
1848      the bottom row.  (So RGB(,,::-1) to pli redraws a copy.)
1849  */
1850 
1851 /*--------------------------------------------------------------------------*/
1852 
1853 func histeq_scale(z, top=, cmin=, cmax=)
1854 /* DOCUMENT histeq_scale(z, top=top_value, cmin=cmin, cmax=cmax)
1855      returns a byte-scaled version of the array Z having the property
1856      that each byte occurs with equal frequency (Z is histogram
1857      equalized).  The result bytes range from 0 to TOP_VALUE, which
1858      defaults to one less than the size of the current palette (or
1859      255 if no pli, plf, or palette command has yet been issued).
1860 
1861      If non-nil CMIN and/or CMAX is supplied, values of Z beyond these
1862      cutoffs are not included in the frequency counts.
1863 
1864    SEE ALSO: bytscl, plf, pli
1865  */
1866 {
1867   if (is_void(top)) top= bytscl([0.,1.])(2);  /* palette size - 1 */
1868   top= long(top);
1869   if (top<0 | top>255) error, "top value out of range 0-255";
1870   y= z(*);
1871   if (!is_void(cmin)) y= y(where(y>=cmin));
1872   if (!is_void(cmax)) y= y(where(y<=cmax));
1873   y= y(sort(y));
1874   x= span(0.,1., numberof(y));
1875   xp= span(0.,1., top+2);
1876   bins= interp(y, x, xp);
1877   list= where(bins(dif)<=0.0);
1878   if (numberof(list)) {
1879     /* some value (or values) of z are repeated many times --
1880        try to handle this by adding a small slope to the sorted y */
1881     dy= y(0)-y(1);
1882     if (!dy) dy= 1.0;
1883     for (eps=1.e-10 ; eps<1000.1 ; eps*=10.) {
1884       bins= interp(y+eps*dy*x, x, xp);
1885       list= where(bins(dif)<=0.0);
1886       if (!numberof(list)) break;
1887     }
1888     if (eps>1000.) error, "impossible error??";
1889   }
1890   return char(max(min(digitize(z,bins)-2,top),0));
1891 }
1892 
1893 func spann(zmin, zmax, n, fudge=)
1894 /* DOCUMENT spann(zmin, zmax, n)
1895      return no more than N equally spaced "nice" numbers between
1896      ZMIN and ZMAX.
1897    SEE ALSO: span, spanl, plc, plfc
1898  */
1899 {
1900   if (is_void(fudge)) fudge= 1.e-12;
1901   reverse= zmin>zmax;
1902   if (reverse) { dz=zmin; zmin=zmax; zmax=dz; }
1903   dz= (zmax-zmin)/max(double(n),0.);
1904   if (!dz) dz= abs(zmin);
1905   if (dz) {
1906     power= floor(log10(dz)+0.00001);
1907     base= dz/10.^power;
1908     if (base>5.00001) { base= 1.0; power+= 1.0; }
1909     else if (base>2.00001) base= 5.0;
1910     else base= 2.0;
1911     /* round dz up to the nearest "nice" number */
1912     dz= base*10.^power;
1913     zmin= ceil(zmin/dz - fudge);
1914     zmax= floor(zmax/dz + fudge);
1915     nz= long(zmax-zmin+1.0);
1916     if (nz>1) {
1917       levs= span(zmin*dz, zmax*dz, nz);
1918     } else {
1919       if (nz<1) {   /* find any nice number in interval */
1920         if (base<1.5) { base= 5.0; power-= 1.0; }
1921         else if (base<2.5) base= 1.0;
1922         else base= 2.0;
1923         dz= base*10.^power;
1924         zmin= ceil(zmin/dz + 0.001);
1925       }
1926       levs= [zmin*dz];
1927     }
1928   } else {
1929     levs= [-1.0,1.0];
1930   }
1931   if (reverse) levs= levs(0:1:-1);
1932   return levs;
1933 }
1934 
1935 /*--------------------------------------------------------------------------*/
1936 
1937 extern _pl_init;
1938 /* xxDOCUMENT _pl_init
1939      initializes the Gist graphics package -- DON'T EVER CALL THIS.
1940  */
1941 _pl_init, GISTPATH; /* ...except right here (see paths.i) */
1942 
1943 /*= SECTION(plothi) higher level plotting functions ========================*/
1944 /* functions which call plg, plf, or other automatic legend generating
1945  * functions must be defined after _pl_init, since that function turns
1946  * on argument "quining" which changes the way things are parsed (yuck) */
1947 
1948 func plmk(y,x,marker=,width=,color=,msize=)
1949 /* DOCUMENT plmk, y,x
1950 
1951      Make a scatter plot of the points Y versus X.  If X is nil,
1952      it defaults to indgen(numberof(Y)).  By default, the marker
1953      cycles through 7 predefined marker shapes.  You may specify a shape
1954      using the marker= keyword, line width using the width= keyword (you
1955      get solid fills for width>=10), color using the color= keyword.
1956      You can also use the msize= keyword to scale the marker (default
1957      msize=1.0).  You can change the default width, color, or msize
1958      using the plmk_default function.
1959 
1960      The predefined marker= values are:
1961 
1962      marker=
1963        1        square
1964        2        cross
1965        3        triangle
1966        4        circle
1967        5        diamond
1968        6        cross (rotated 45 degrees)
1969        7        triangle (upside down)
1970 
1971      You may also put marker=[xm,ym] where xm and ym are vectors
1972      of NDC coordinates to design your own custom marker shapes.
1973 
1974    SEE ALSO: plmk_default, plg (type=0 keyword), pleb
1975  */
1976 {
1977   if (is_void(marker)) {
1978     marker= (_plmk_count-1)%7 + 1;
1979     _plmk_count++;
1980   }
1981   if (numberof(marker)==1) {
1982     marker= *_plmk_markers(marker);
1983   } else if (dimsof(marker)(1)!=2 || dimsof(marker)(3)!=2 ||
1984              dimsof(marker)(2)<=2) {
1985     error, "illegal marker= keyword value";
1986   }
1987   xm= marker(,1);
1988   ym= marker(,2);
1989   if (is_void(msize)) msize= _plmk_msize;
1990   if (!is_void(msize)) {
1991     xm*= msize;
1992     ym*= msize;
1993   }
1994   if (is_void(color)) color= _plmk_color;
1995   if (structof(color)==string) {
1996     n= where(color==["bg","fg","black","white",
1997                      "red","green","blue","cyan","magenta","yellow",
1998                      "grayd","grayc","grayb","graya"]);
1999     if (numberof(n)!=1) error, "unrecognized color name: "+color;
2000     color= char(-n(1));
2001   }
2002   ecolor= color;
2003   if (is_void(width)) width= _plmk_width;
2004   if (!is_void(width)) {
2005     if (width>=10) {
2006       solid= 1;
2007       if (is_void(color)) color= ecolor= char(-2);
2008       z= array(char(color), 1+numberof(y));
2009       width= [];
2010     }
2011   }
2012   n= array(1,1+numberof(y));
2013   n(1)= numberof(ym);
2014   if (is_void(x)) x= indgen(numberof(y));
2015   plfp, z,grow(ym,y),grow(xm,x),n,edges=1,ewidth=width,ecolor=ecolor;
2016 }
2017 
2018 func plmk_default(color=, msize=, width=)
2019 /* DOCUMENT plmk_default, color=color, msize=msize, width=width
2020 
2021      sets default color, msize, and width values for plmk.  Use
2022      width=10 to get solid fills.  With no parameters, plmk_default
2023      restores the initial default values.
2024 
2025    SEE ALSO: plmk
2026  */
2027 {
2028   { extern _plmk_color, _plmk_width, _plmk_msize; }
2029   i= 0;
2030   if (!is_void(color)) _plmk_color= color;
2031   else i++;
2032   if (!is_void(width)) _plmk_width= width;
2033   else i++;
2034   if (!is_void(msize)) _plmk_msize= msize;
2035   else i++;
2036   if (i==3) _plmk_msize= _plmk_color= _plmk_width= [];
2037 }
2038 
2039 _plmk_count= 1;
2040 _plmk_msize= _plmk_color= _plmk_width= [];
2041 /* predefined markers: square, +, delta, circle, diamond, x, grad */
2042 _plmk_markers= span(-pi,pi,37)(zcen);
2043 _plmk_markers= [&([[-1,1,1,-1],[-1,-1,1,1]]*.007),
2044                 &([[-4,-1,-1,1,1,4,4,1,1,-1,-1,-4],
2045                    [-1,-1,-4,-4,-1,-1,1,1,4,4,1,1]]*.007/sqrt(7)),
2046                 &([[-sqrt(3),sqrt(3),0],[-1,-1,2]]*.007/sqrt(.75*sqrt(3))),
2047                 &([cos(_plmk_markers),sin(_plmk_markers)]*.007/(pi/4.)),
2048                 &([[-1,0,1,0],[0,-1,0,1]]*.007*sqrt(2)),
2049                 &([[-1,-2.5,-1.5,0,1.5,2.5,1,2.5,1.5,0,-1.5,-2.5],
2050                    [0,-1.5,-2.5,-1,-2.5,-1.5,0,1.5,2.5,1,2.5,1.5]]*.007*
2051                   sqrt(2)/sqrt(7)),
2052                 &([[0,sqrt(3),-sqrt(3)],[-2,1,1]]*.007/sqrt(.75*sqrt(3)))];
2053 
2054 func plfc(z, y, x, ireg, levs=, colors=, region=, triangle=)
2055 /* DOCUMENT plfc, z, y, x, levs=z_values
2056          or plfc, z, y, x, ireg, levs=z_values
2057 
2058      fills contours of Z on the mesh Y versus X.  Y, X, and IREG are
2059      as for plm.  The Z array must have the same shape as Y and X.
2060      The function being contoured takes the value Z at each point
2061      (X,Y) -- that is, the Z array is presumed to be point-centered.
2062 
2063      The LEVS keyword is a list of the values of Z at which you want
2064      contour curves.  These curves divide the mesh into numberof(LEVS)+1
2065      regions, each of which is filled with a solid color.  If LEVS is
2066      nil, up to 19 "nice" equally spaced level values spanning the
2067      range of Z are selected.  The level values actually used are
2068      always output to the external variable plfc_levs.
2069 
2070      If you specify levs=, you may also specify colors= a list of
2071      colors of length numberof(LEVS)+1.  The colors should be indices
2072      into the current palette.  If you do not specify them, equally
2073      spaced colors are chosen.
2074 
2075      The following keywords are legal (each has a separate help entry):
2076    KEYWORDS: triangle, region
2077    SEE ALSO: plg, plm, plc, plv, plf, pli, plt, pldj, plfp, plmesh
2078              color_bar, spann, contour, limits, logxy, range, fma, hcp
2079  */
2080 {
2081   zmin= min(z);
2082   zmax= max(z);
2083   if (is_void(levs)) {
2084     levs= spann(zmin, zmax, 20, fudge=-0.05);
2085   } else if (numberof(levs)>1) {
2086     levs = double(levs);
2087     dz= levs(dif); /* blows up if <2 or not numeric */
2088     reverse= max(dz);
2089     if (numberof(dz)!=numberof(levs)-1 ||
2090         anyof((dz>0.)!=(reverse>0.)) || !reverse)
2091       error, "levs= values must be monotone 1D";
2092     reverse= reverse<0.;
2093     if (reverse) levs= levs(0:1:-1);
2094     else levs= levs(1:0);
2095   } else {
2096     levs= [double(levs(1))];
2097   }
2098   { extern plfc_levs, plfc_colors; }
2099   plfc_levs= levs;
2100   n= numberof(levs);
2101 
2102   pairs= [grow([min(-1.e30,1.1*zmin)],levs),
2103           grow(levs,[max( 1.e30,1.1*zmax)])];
2104   if (reverse) pairs= pairs(0:1:-1,);
2105 
2106   /* make sure some kind of reasonable palette is installed */
2107   { local nc, yc, xc; }
2108   palette, query=1, nc, yc, xc;
2109   nc= numberof(nc);
2110   if (nc<3) {
2111     palette, "earth.gp";
2112     palette, query=1, nc, yc, xc;
2113     nc= numberof(nc);
2114   }
2115 
2116   if (is_void(colors)) {
2117     colors= char(span(0,nc-1,n+2)(zcen));
2118   } else {
2119     if (numberof(colors)!=n+1)
2120       error, "colors= must specify one more color than levs=";
2121     if (structof(colors)!=char) {
2122       cmin= min(colors);
2123       cmax= max(colors);
2124       dz= 0.5*(cmax-cmin)/double(n+1);
2125       colors= bytscl(colors,cmin=cmin-dz,cmax=cmax+dz);
2126     }
2127   }
2128   plfc_colors= colors;
2129 
2130   if (is_void(triangle)) triangle= array(short,dimsof(z));
2131 
2132   for (i=1 ; i<=n+1 ; ++i) {
2133     pair= pairs(i,);
2134     if (pair(2)<zmin || pair(1)>zmax) continue;
2135     nc= contour(yc,xc, pair,z,y,x,ireg,triangle=triangle);
2136     if (!numberof(nc)) continue;
2137     plfp,array(colors(i),numberof(nc)),yc,xc,nc,edges=0;
2138   }
2139 }
2140 
2141 func color_bar(levs, colors, vert=, labs=, adjust=, ecolor=)
2142 /* DOCUMENT color_bar
2143          or color_bar, levs, colors
2144      Draw a color bar below the current coordinate system.  If LEVS is
2145      not specified uses plfc_levs (set by previous call to plfc).  If
2146      COLORS is specified, it should have one more value than LEVS,
2147      otherwise equally spaced colors are chosen, or plfc_colors if
2148      plfc_levs was used.  With the vert=1 keyword the color bar appears
2149      to the left of the current coordinate system (vert=0 is default).
2150      By default, color_bar will attempt to label some of the color
2151      interfaces.  With the labs= keyword, you can force the labelling
2152      algorithm as follows: labs=0 supresses all labels, labs=n forces
2153      a label at every nth interface, labs=[i,n] forces a label at every
2154      nth interface starting from interface i (0<=i<=numberof(LEVS)).
2155      You can use the adjust= keyword to move the bar closer to (adjust<0)
2156      or further from (adjust>0) the viewport, and the height= keyword to
2157      set the height of any labels (default 14 points).
2158    SEE ALSO: plfc
2159  */
2160 {
2161   if (is_void(levs)) {
2162     if (is_void(plfc_levs)) error, "no levels specified";
2163     levs= plfc_levs;
2164     n= numberof(levs)+1;
2165     if (is_void(colors)) colors= plfc_colors;
2166   } else {
2167     n= numberof(levs)+1;
2168     if (is_void(colors)) colors= bytscl(span(1,n,n),cmin=0.5,cmax=n+0.5);
2169   }
2170   if (n != numberof(colors))
2171     error, "numberof(colors) must be one more than numberof(levs)";
2172 
2173   port= viewport();
2174   if (is_void(adjust)) adjust= 0.;
2175   dx= dy= 0.;
2176   if (vert) {
2177     x= (port(2)+adjust+[0.022,0.042])(-:1:n+1,);
2178     dx= 0.005;
2179     y= span(port(3),port(4),n+1)(,-:1:2);
2180   } else {
2181     y= (port(3)-adjust-[0.045,0.065])(-:1:n+1,);
2182     dy= -0.005;
2183     x= span(port(1),port(2),n+1)(,-:1:2);
2184   }
2185   sys= plsys(0);
2186   plf,[colors],y,x,edges=1,ecolor=ecolor, legend="";
2187   plsys, sys;
2188 
2189   if (is_void(labs) || labs(0)>0) {
2190     if (numberof(levs)>1) {
2191       dz= levs(dif);
2192       if (numberof(dz)!=numberof(levs)-1 ||
2193           anyof((dz>0.)!=(dz(1)>0.)) || !dz(1))
2194         error, "levs must be monotone 1D";
2195       levs= levs(1:0);
2196       levs= grow([2*levs(1)-levs(2)],levs,[2*levs(0)-levs(-1)]);
2197     } else {
2198       levs= double(levs(1));
2199       if (!levs) levs= [-1.,levs,1.];
2200       else levs= [0.,levs,2*levs];
2201     }
2202     if (numberof(labs)<2) {
2203       if (is_void(labs)) labs= (n-1)/4 + 1;
2204       orig= where(levs<1.e-9*max(levs(dif)));
2205       if (numberof(orig)==1) labs= [orig(1)%labs,labs];
2206       else labs= [(n%labs)/2,labs];
2207     }
2208     list= where(indgen(0:n)%labs(2)==labs(1));
2209     x= x(list,);
2210     y= y(list,);
2211     labs= swrite(format="%g",levs(list));
2212     plsys, 0;
2213     pldj, x(,2),y(,2),x(,2)+dx,y(,2)+dy, legend="";
2214     plsys, sys;
2215     plt1, labs,x(,2)+dx,y(,2)+dy, justify=(vert?"LH":"CT"), height=height,
2216       font="helvetica";
2217   }
2218 }
2219 
2220 /* pleb from Regis Lachaume 2003 */
2221 func pleb(y, x, dx=, dy=, mfill=, color=, width=, marker=, msize=)
2222 /* DOCUMENT pleb, y, x, dx=dx, dy=dy
2223      plots Y vs. X with error bars.
2224 
2225      Uncertainty on X and/or Y are specified with the dx= and dy= keywords.
2226      X and Y must have same dimensions, dx= and dy= must be conformable
2227      with X (or Y).  Either dx or dy may be nil for no error bar in that
2228      direction.  Scalar dx or dy gives equal error bars at all points,
2229      dimsof(dx)==dimsof(X), etc., gives different error bar at each point.
2230      dx= and dy= may also have a trailing dimension of length 2 in order
2231      to get asymmetric error bars; dx(..,1) is the lower error bar length,
2232      and dx(..,2) is the upper error bar length in that case, etc.
2233 
2234      If marker=, msize=, or width= is specified, markers are positioned
2235      at X, Y using plmk.  Use the mfill=1 keyword to get filled markers
2236      (width>=10. in plmk; width= refers to error bar width in pleb).
2237 
2238    EXAMPLE:
2239       x = [0, 1, 2, 3];
2240       y = [0, 2, 4, 7];
2241       pleb, y, x, dx=0.2, dy=[0.3, 0.4, 0.5, 0.3], mfill=1;
2242          Uncertainties on dx are the same for all X, and those
2243          on Y are different for each value of Y.  Filled markers
2244          will be displayed at (X, Y).
2245 
2246    KEYWORDS: color, width, marker, msize
2247       dx     uncertainty on X
2248       dy     uncertainty on Y
2249 
2250    SEE ALSO: plmk, pldj
2251  */
2252 {
2253   if (is_void(dx)) dx = 0.;
2254   if (is_void(dy)) dy = 0.;
2255 
2256   xmin = x-dx;
2257   xmax = x+dx;
2258   if (numberof(x) != numberof(xmin)) {
2259     xmin = xmin(..,1);
2260     xmax = xmax(..,2);
2261   }
2262 
2263   ymin = y-dy;
2264   ymax = y+dy;
2265   if (numberof(y) != numberof(ymin)) {
2266     ymin = ymin(..,1);
2267     ymax = ymax(..,2);
2268   }
2269 
2270   pldj, x, ymin, x, ymax, color=color, width=width, legend="";
2271   pldj, xmin, y, xmax, y, color=color, width=width, legend="";
2272   if (!is_void(marker) || !is_void(msize) || !is_void(mfill))
2273     plmk, y, x, color=color, msize=msize, marker=marker,
2274       width=(mfill? 20.: width);
2275 }
2276 
2277 /*--------------------------------------------------------------------------*/
2278