Debian Codegraph @

texmf-dist/metapost/base/graph.mp

raw
1 % $Id: graph.mp,v 1.2 2004/09/19 21:47:10 karl Exp $
2 % Public domain.
3
4 % Macros for drawing graphs
5
6 % begingraph(width,height) begin a new graph
7 % setcoords(xtype,ytype) sets up a new coordinate system (log,-linear..)
8 % setrange(lo,hi) set coord ranges (numeric and string args OK)
9 % gdraw <file or path> [with...] draw a line in current coord system
10 % gfill <file or path> [with...] fill a region using current coord system
11 % gdrawarrow .., gdrawdblarrow.. like gdraw, but with 1 or 2 arrowheads
12 % Mreadpath(<filename>) read path from file and return it in Mlog form
13 % augment<path name>(loc) append given coordinates to a polygonal path
14 % glabel<suffix>(pic,loc) place label pic near graph coords or time loc
15 % gdotlabel<suffix>(pic,loc) same with dot
16 % OUT loc value for labels relative to whole graph
17 % gdata(file,s,text) read coords from file; evaluate t w/ tokens s[]
18 % auto.<x or y> default x or y tick locations (for interation)
19 % itick.<bot|top|..>(fmt,u) draw inward tick from given side at u w/ format
20 % otick.<bot|top|..>(fmt,u) draw outward tick at coord u; label format fmt
21 % grid.<bot|top|..>(fmt,u) draw grid line at u with given side labelled
22 % autogrid([itick|.. bot|..],..) iterate over auto.x, auto.y, drawing tick/grids
23 % frame.[bot|top..] draw frame (or one side of the frame)
24 % endgraph end of graph--the result is a picture
25
26 % option `plot <picture>' draws picture at each path knot, turns off pen
27 % Gtemplate.<tickcmd> template paths for tick marks and grid lines
28 % Gmargin.low, Gmargin.high fractions determining margins when no setrange
29 % Glmarks[], Gumarks, Gemarks loop text strings used by auto.<x or y>
30 % Gmarks, Gminlog numeric parameters used by auto.<x or y>
31 % Gpaths tells how to interpret paths: log or linear
32 % Autoform is the format string used by autogrid
33
34 % Other than the above-documented user interface, all externally visible names
35 % are of the form X_.<suffix>, Y_.<suffix>, or Z_.<suffix>, or they start
36 % with `G' and end with `_'.
37
38
39 if unknown Mzero:
40 begingroup interim % marith.mp starts with `warningcheck:=0'
41 input marith
42 endgroup; % restore warningcheck; we zero it when necessary
43 fi
44 if unknown mant_font:
45 input format
46 fi
47
48
49 vardef Gerr_(expr x,s) =
50 interim showstopping:=0;
51 show x; errmessage s;
52 enddef;
53
54
55
56 %%%%%%%%%%%%%%%%%%%%%%%% Data structures, begingraph %%%%%%%%%%%%%%%%%%%%%%%%
57
58 vardef Z_@# = (X_@#,Y_@#) enddef; % used in place of plain.mp's z convention
59
60 def Gsuf_(suffix $) = % convert from x or y to X_ or Y_
61 if str$="x": X_ else: Y_ fi
62 enddef;
63
64
65 def begingraph(expr w, h) =
66 begingroup
67 save X_, Y_, Gfin_, Gcur_, Gcbb_, Gneedgr_, Gneedfr_, Gdidsc_;
68 save Gdpic_, Gppic_, Ggl_, Garw_;
69 picture Gfin_, Gcur_, Gcbb_, Gdpic_, Gppic_, Ggl_[];
70 boolean Gneedgr_, Gneedfr_, Gdidsc_;
71 Gfin_ = nullpicture; % the finished part of the graph
72 Gcur_ = nullpicture; % what has been drawn in current coords
73 Gcbb_ = nullpicture; % picture whose bbox is Gcur_'s w/ linewidths 0
74 X_.ctyp = Y_.ctyp = linear; % coordinate system for each axis
75 Z_.gdim = (w,h); % dimensions of graph not counting axes etc.
76 X_.sc = Y_.sc = 0; % Mlog(the amount Gcur_ has been descaled by)
77 Gneedgr_ = true; % whether autogrid is needed
78 Gneedfr_ = true; % whether frame needs to be drawn
79 Gdidsc_ = false; % set when Glinsc_ rescales coordinates
80 Gdpic_ = nullpicture; % result of last gdraw or gfill
81 Garw_ = 0; % number of arrowheads for next gdraw
82 enddef;
83
84 % Additional variables not explained above:
85 % Z_.low, Z_.high user-specified coordinate ranges in units used in Gcur_
86 % Gppic_ a picture from the `plot' option known when plot allowed
87 % Gmll_, Gmhh_ pairs giving bounds used in auto<x or y>
88 % Gme_, Gcma_ variables and macros used in auto<x or y>
89 % Gc_ temporary macro used in auto<x or y>
90 % Gbias_ an offset to Gmll_ and Gmhh_ to ease computing exponents
91 % Ggl_[] labels to place around the whole graph when it is done
92 % Some additional variables function as constants. Most can be modified by the
93 % user to alter the behavior of these macros.
94 % Not very modifiable: log, linear, Gboff_, Gfra_, Gfrb_, Gmarg_
95 % Modifiable: Gtemplate.suffix, Glmarks[], Gumarks, Gemarks, Gmarks,
96 % Gminlog, Gpaths, Autoform
97
98
99 newinternal log, linear; % coordinate system codes
100 newinternal Gpaths; % path interpretation parameter
101 log:=1; linear:=2;
102 Gpaths := linear;
103
104
105
106 %%%%%%%%%%%%%%%%%%%%%% Coordinates: setcoords, setrange %%%%%%%%%%%%%%%%%%%%%%
107
108 % Graph-related usr input is `user graph coordinates' as specified by arguments
109 % to setcoords.
110 % `Internal graph coordinates' are used for Gcur_, Gcbb_, Z_.low, Z_.high.
111 % Their meaning depends on the appropriate component of Z_.ctyp:
112 % log means internal graph coords = Mlog(user graph coords)
113 % -log means internal graph coords = -Mlog(user graph coords)
114 % linear means internal graph coords = Mexp(Mlog(user graph coords) Mdiv ?sc)
115 % -linear means internal graph coords = -Mexp(Mlog(user graph coords) Mdiv ?sc)
116 % (In the last two lines, `?sc' means X_.sc or Y_.sc as appropriate.)
117
118
119 vardef Gsetp_ = % Set default Z_.low, Z_.high
120 forsuffixes $=low,high:
121 (if known X_$: whatever else: X_$ fi, if known Y_$: whatever else: Y_$ fi)
122 = Gmargin$[llcorner Gcbb_,urcorner Gcbb_] + Gmarg_$;
123 endfor
124 enddef;
125 pair Gmarg_.low, Gmarg_.high;
126 Gmarg_.high=-Gmarg_.low=(.00002,.00002);
127
128
129 % Set $, $$, $$$ so that shifting by $ then transforming by $$ and then $$$
130 % maps the essential bounding box of Gcur_ into (0,0)..Z_.gdim. The
131 % `essential bounding box' is either what Z_.low and Z_.high imply or the
132 % result of ignoring pen widths in Gcur_.
133 vardef Gsetsc_(suffix $,$$,$$$) =
134 save p_;
135 Gsetp_;
136 pair p_, $; $=Gboff_-Z_.low;
137 p_ = (max(X_.high-X_.low,.9), max(Y_.high-Y_.low,.9));
138 transform $$, $$$;
139 forsuffixes #=$$,$$$: xpart#=ypart#=xypart#=yxpart#=0; endfor
140 (Z_.high+Gboff_+$) transformed $$ = p_;
141 p_ transformed $$$ = Z_.gdim;
142 enddef;
143 Gmargin.low=-.07; % bbox fraction for default range start
144 Gmargin.high=1.07; % bbox fraction for default range stop
145 pair Gboff_; Gboff_=epsilon*(3,3); % allowance to avoid numerical trouble
146
147
148 def Gwithpc_(expr q) =
149 withpen penpart q withcolor
150 if colormodel q=1:
151 false
152 elseif colormodel q=3:
153 (greypart q)
154 elseif colormodel q=5:
155 (redpart q, greenpart q, bluepart q)
156 elseif colormodel q=7:
157 (cyanpart q, magentapart q, yellowpart q, blackpart q)
158 fi
159 enddef;
160
161 % Add picture component q to picture @# and change part p to tp, where p is
162 % something from q that needs coordinate transformation. The type of p is pair
163 % or path.
164 % Pair o is the value of p that makes tp (0,0). This implements the trick
165 % whereby using 1 instead of 0 for th the width or height or the setbounds path
166 % for a label picture supresses shifting in x or y.
167 vardef old_Gpconv_@#(expr q, o)(text tp) =
168 save p;
169 if stroked q:
170 path p; p=pathpart q;
171 addto @# doublepath tp Gwithpc_(q) dashed dashpart q;
172 elseif filled q:
173 path p; p=pathpart q;
174 addto @# contour tp Gwithpc_(q);
175 else:
176 interim truecorners:=0;
177 pair p; p=llcorner q;
178 if urcorner q<>p: p:=p+Gcmul_(o-p,urcorner q-p); fi
179 addto @# also q shifted ((tp)-llcorner q);
180 fi
181 enddef;
182 % TH: new version from code found at sarovar tracker. This makes
183 % grdaw clip the result to the window defined with setrange
184 vardef Gpconv_@#(expr q, o)(text tp) =
185 save p, tp_geclipt;
186 picture tp_geclipt; tp_geclipt:=nullpicture;
187 if stroked q:
188 path p; p=pathpart q;
189 %%% --- SDV added
190 addto tp_geclipt doublepath tp Gwithpc_(q) dashed dashpart q;
191 clip tp_geclipt to origin--(xpart Z_.gdim,0)--Z_.gdim--(0, ypart Z_.gdim)--cycle;
192 addto @# also tp_geclipt;
193 %%%
194 %%% --- SDV deleted
195 %%addto @# doublepath tp Gwithpc_(q) dashed dashpart q;
196 %%%
197 elseif filled q:
198 path p; p=pathpart q;
199 addto @# contour tp Gwithpc_(q);
200 else:
201 interim truecorners:=0;
202 pair p; p=llcorner q;
203 if urcorner q<>p: p:=p+Gcmul_(o-p,urcorner q-p); fi
204 addto @# also q shifted ((tp)-llcorner q);
205 fi
206 enddef;
207
208 def Gcmul_(expr a,b) = (xpart a*xpart b, ypart a*ypart b) enddef;
209
210
211 vardef Gclbnds_@# = numeric @#.low, @#.high; enddef;
212
213
214 % Finalize anything drawn in the present coordinate system and set up a new
215 % system as requested
216 vardef setcoords(expr tx, ty) =
217 interim warningcheck:=0;
218 if length Gcur_>0:
219 save s, S, T;
220 Gsetsc_(s, S, T);
221 for q within Gcur_:
222 Gpconv_.Gfin_(q, -s, p shifted s transformed S transformed T);
223 endfor
224 Gcur_ := Gcbb_ := nullpicture;
225 fi
226 Gclbnds_.X_; Gclbnds_.Y_;
227 X_.ctyp:=tx; Y_.ctyp:=ty;
228 enddef;
229
230
231 % Use scaling command cc to rescale everything in internal graph coords so that
232 % if Mlog(user graph coords) is u then the internal graph coord value becomes
233 % 10000/128. Assume u>=$sc+4Mten where $ is X_ or Y_, depending on whether cc
234 % is xscaled or yscaled.
235 vardef Glinsc_@#(expr u)(text cc) =
236 save v, P;
237 v = mexp(4Mten + (@#sc-u));
238 picture P; P=nullpicture;
239 for q within Gcur_: Gpconv_.P(q, origin, p cc v cc 1/128); endfor
240 Gcur_ := P;
241 Gcbb_ := Gcbb_ cc v cc 1/128;
242 forsuffixes $=low, high:
243 if known @#.$: @#.$:=@#.$*v/128; fi
244 endfor
245 @#sc:= Mabs u -1115.72742; % @#sc:=Mabs u+Mlog(128)-4Mten
246 Gdidsc_ := true;
247 enddef;
248
249
250 % Convert x coordinate u from Mlog(user graph coords) to ctyp=linear internal
251 % graph coords. If the result would be uncomfortably large, use Glinsc_ to
252 % descale as needed.
253 vardef Gxcvlin_ primary u =
254 interim warningcheck:=0;
255 if unknown u: u
256 elseif u>X_.sc+4Mten:
257 Glinsc_.X_(u,xscaled);
258 78.125
259 else: Mexp(u Mdiv X_.sc)
260 fi
261 enddef;
262
263 vardef Gycvlin_ primary u = % same as Gxcvlin_ but u is a y coordinate
264 interim warningcheck:=0;
265 if unknown u: u
266 elseif u>Y_.sc+4Mten:
267 Glinsc_.Y_(u,yscaled);
268 78.125
269 else: Mexp(u Mdiv Y_.sc)
270 fi
271 enddef;
272
273
274 % Set Z_.low and Z_.high to correspond to given range of user graph
275 % coordinates. The text argument should be a sequence of pairs and/or strings
276 % with 4 components in all.
277 vardef setrange(text t) =
278 interim warningcheck:=0;
279 save r_; r_=0;
280 string r_[]s;
281 for x_=
282 for p_=t: if pair p_: xpart p_, ypart fi p_, endfor:
283 r_[incr r_] if string x_: s fi = x_;
284 if r_>2:
285 Gsetr_ if r_=3: X_(Gxcvlin_) else: Y_(Gycvlin_) fi(
286 r_[r_-2] if unknown r_[r_-2]: s fi, x_);
287 fi
288 exitif r_=4;
289 endfor
290 enddef;
291
292
293 % @# is X_ or Y_; $ is Gxcvlin_ or Gycvlin_; l and h are numeric or string
294 % It would not be OK to set (@#low,@#high) to a pair expression because $ might
295 % try to rescale @#low when evaluating the right-hand side for @#high.
296 vardef Gsetr_@#(suffix $)(expr l, h) =
297 Gclbnds_@#;
298 if @#ctyp>0:
299 @#low = if abs @#ctyp<>log: $ fi Mlog_Str l;
300 @#high = if abs @#ctyp<>log: $ fi Mlog_Str h;
301 else:
302 -@#high = if abs @#ctyp<>log: $ fi Mlog_Str l;
303 -@#low = if abs @#ctyp<>log: $ fi Mlog_Str h;
304 fi
305 enddef;
306
307
308
309
310
311 %%%%%%%%%%%%%%%%%%%%%%%%% Converting path coordinates %%%%%%%%%%%%%%%%%%%%%%%%%
312
313 % Find the result of scanning path p and using macros tx and ty to adjust the
314 % x and y parts of each coordinate pair. Boolean paramter c tells whether to
315 % force the result to be polygonal.
316 vardef Gscan_(expr p, c)(suffix tx, ty) =
317 if (str tx="") and (str ty=""): p
318 else:
319 save r_; path r_;
320 forever:
321 Gdidsc_ := false;
322 r_ := Gpp_(point 0 of p, tx, ty)
323 if path p:
324 for t=1 upto length p:
325 if c: --
326 else: ..controls Gpp_(postcontrol(t-1) of p, tx, ty)
327 and Gpp_(precontrol t of p, tx, ty) ..
328 fi
329 Gpp_(point t of p, tx, ty)
330 endfor
331 if cycle p: &cycle fi
332 fi;
333 exitunless Gdidsc_;
334 endfor
335 if pair p: point 0 of fi r_
336 fi
337 enddef;
338 vardef Gpp_(expr p)(suffix tx, ty) = (tx xpart p, ty ypart p) enddef;
339
340
341 % Convert path p from Mlog(user graph coords) to internal graph coords.
342 % Boolean flag f says whether to force the result to be polygonal.
343 vardef GMcvi_(expr f) primary p =
344 Gscan_(p, f,
345 if abs X_.ctyp=linear: Gxcvlin_ fi,
346 if abs Y_.ctyp=linear: Gycvlin_ fi)
347 if X_.ctyp<0: xscaled -1 fi
348 if Y_.ctyp<0: yscaled -1 fi
349 enddef;
350
351
352 % Convert path p from user graph coords to internal graph coords.
353 vardef Gucvi_ primary p =
354 if Gpaths=log:
355 GMcvi_((abs X_.ctyp<>log) or (abs Y_.ctyp<>log)) p
356 else:
357 interim warningcheck:=0;
358 save t, u;
359 t=Mexp(-X_.sc); u=Mexp(-Y_.sc);
360 Gscan_(p, (abs X_.ctyp<>linear) or (abs Y_.ctyp<>linear),
361 if abs X_.ctyp=log: Mlog fi,
362 if abs Y_.ctyp=log: Mlog fi)
363 transformed (identity
364 if abs X_.ctyp=linear: xscaled t fi
365 if abs Y_.ctyp=linear: yscaled u fi
366 if X_.ctyp<0: xscaled -1 fi
367 if Y_.ctyp<0: yscaled -1 fi)
368 fi
369 enddef;
370
371
372 % Convert label location t_ from user graph coords to internal graph coords.
373 % The label location should be a pair, or two numbers/strings. If t_ is empty
374 % or a single item of non-pair type, just return t_. Unknown coordinates
375 % produce unknown components in the result.
376 vardef Gtcvi_(text t_) =
377 save n_; n_=0;
378 interim warningcheck:=0;
379 if 0 for x_=t_: +1 if pair x_: +1 fi endfor <= 1:
380 t_
381 else:
382 n_0 = n_1 = 0;
383 point 0 of GMcvi_(true) (
384 for x_=
385 for y_=t_: if pair y_: xpart y_, ypart fi y_, endfor
386 0, 0:
387 if known x_: Mlog_Str x_
388 else: hide(n_[n_]:=whatever) Mzero
389 fi
390 exitif incr n_=2;
391 ,endfor) + (n_0,n_1)
392 fi
393 enddef;
394
395
396
397 %%%%%%%%%%%%%%%%%%%%%%%%%%%%% Reading data files %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
398
399 % Read a line from file f, extract whitespace-separated tokens ignoring any
400 % initial "%", and return true if at least one token is found. The tokens
401 % are stored in @#1, @#2, .. with "" in the last @#[] entry.
402 vardef Grdln_@#(expr f) =
403 save n_, s_; string s_;
404 s_ = readfrom f;
405 string @#[];
406 if s_<>EOF:
407 @#1 := loptok s_;
408 n_ = if @#1="%": 0 else: 1 fi;
409 forever:
410 @#[incr n_] := loptok s_;
411 exitif @#[n_]="";
412 endfor
413 @#1<>""
414 else: false
415 fi
416 enddef;
417
418
419 % Execute c for each line of data read from file f, and stop at the first
420 % line with no data. Commands c can use line number i and tokens $1, $2, ...
421 def gdata(expr f)(suffix $)(text c) =
422 for i=1 upto infinity:
423 exitunless Grdln_$(f);
424 c
425 endfor
426 enddef;
427
428
429 % Read a path from file f and return it in Mlog form. The path is terminated
430 % by blank line or EOF.
431 vardef Mreadpath(expr f) =
432 interim warningcheck:=0;
433 save s;
434 gdata(f, s, if i>1:--fi
435 if s2="": (Mlog i, Mlog_str s1)
436 else: (Mlog_str s1, Mlog_str s2) fi)
437 enddef;
438
439
440 % Append coordinates t to polygonal path @#. The coordinates can be numerics,
441 % strings, or a single pair.
442 vardef augment@#(text t) =
443 interim warningcheck := 0;
444 if not path begingroup @# endgroup:
445 Gerr(begingroup @# endgroup, "Cannot augment--not a path");
446 else:
447 def Gcma_= hide(def Gcma_=,enddef) enddef;
448 if known @#: @#:=@#-- else: @#= fi
449 (for p=t:
450 Gcma_ if string p: Mexp Mlog_str fi p
451 endfor);
452 fi
453 enddef;
454
455
456
457 %%%%%%%%%%%%%%%%%%%%%%%%%%%%% Drawing and filling %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
458
459 % Unknown pair components are set to 0 because glabel and gdotlabel understand
460 % unknown coordinates as `0 in absolute units'.
461 vardef Gupbb_(expr p) =
462 interim warningcheck:=0; % This is needed because Gupbb_ has to work with internal graph coordinates which may be in Mlog form.
463 if known p: addto Gcbb_ doublepath p;
464 else:
465 save x,y;
466 z = llcorner Gcbb_;
467 if unknown xpart p: xpart p= else: x:= fi 0;
468 if unknown ypart p: ypart p= else: y:= fi 0;
469 addto Gcbb_ doublepath (p+z);
470 fi
471 Gcbb_ := image(fill llcorner Gcbb_..urcorner Gcbb_--cycle);
472 enddef;
473
474
475 % Initiate a gdraw or gfill command. This must be done before scanning the
476 % argument, because that could invoke the `if known Gppic_' test in a following
477 % plot option .
478 def Gaddto_ = Gdpic_:=Gppic_:=nullpicture; addto Gdpic_ enddef;
479
480
481 % Handle the part of a Gdraw command that uses path or data file p.
482 def Gdraw_ expr p =
483 if string p: GMcvi_(true) Mreadpath(p)
484 elseif path p or pair p: Gucvi_ p
485 else: Gerr_(p,"gdraw argument should be a data file or a path")
486 origin
487 fi
488 withpen currentpen Gwithlist_ _op_
489 enddef;
490
491
492 % Handle the part of a Gdraw command that uses path or data file p.
493 def Gfill_ expr p =
494 if string p: GMcvi_(true) Mreadpath(p) --cycle
495 elseif cycle p: Gucvi_ p
496 else: Gerr_(p,"gfill argument should be a data file or a cyclic path")
497 origin..cycle
498 fi Gwithlist_ _op_
499 enddef;
500
501 def gdraw = Gaddto_ doublepath Gdraw_ enddef;
502 def gfill = Gaddto_ contour Gfill_ enddef;
503
504
505 % This is used in Gdraw_ and Gfill_ to allow postprocessing Gdpic_
506 def Gwithlist_ text t_ = t_; Gpostdr_; enddef;
507
508
509 % Set Gppic_ so the postprocessing step will plot picture p at each path knot.
510 % Also select nullpen to supress stroking.
511 def plot expr p =
512 if known Gppic_:
513 withpen nullpen
514 hide (Gppic_:=image(
515 if bounded p: for q within p: Gdrw_ q endfor % Save memory
516 else: Gdrw_ p
517 fi Gsetb_ origin..cycle))
518 fi
519 enddef;
520
521 % This hides a semicolon that could prematurely end Gwithlist_'s text argument
522 def Gdrw_ primary p = addto currentpicture also p; enddef;
523 def Gsetb_ = setbounds currentpicture to enddef;
524
525
526 def gdrawarrow = Garw_:=1; gdraw enddef;
527 def gdrawdblarrow = Garw_:=2; gdraw enddef;
528
529
530 % Post-process the filled or stroked picture Gdpic_ as follows: (1) update
531 % the bounding box information; (2) transfer it to Gcur_ unless the pen has
532 % been set to nullpen to disable stroking; (3) plot Gppic at each knot.
533 vardef Gpostdr_ =
534 save p;
535 path p; p=pathpart Gdpic_;
536 Gupbb_(p);
537 if filled Gdpic_ or not Gisnull_(penpart Gdpic_):
538 addto Gcur_ also Gdpic_;
539 fi
540 if length Gppic_>0:
541 for i=0 upto length p if cycle p: -1 fi:
542 addto Gcur_ also Gppic_ shifted point i of p;
543 endfor
544 picture Gppic_;
545 fi
546 if Garw_>0:
547 Garwhd_(p, Gwithpc_(Gdpic_));
548 if Garw_>1: Garwhd_(reverse p, Gwithpc_(Gdpic_)); fi
549 Garw_:=0;
550 fi
551 enddef;
552 vardef Gisnull_(expr p) = (urcorner p=origin) and (llcorner p=origin) enddef;
553
554
555 vardef Garwhd_(expr p)(text w) = % Draw arrowhead for path p, with list w
556 addto Gcur_ also
557 image(filldraw arrowhead(
558 Garhwext_(precontrol infinity of p, point infinity of p)) w;
559 Gsetb_ point infinity of p..cycle);
560 enddef;
561
562 vardef Garhwext_(expr p, q) =
563 if p<>q: (q - 100pt*unitvector(q-p)) -- fi
564 q
565 enddef;
566
567
568
569 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Drawing labels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
570
571 % Argument c is a drawing command that needs an additonal argument p that gives
572 % a location in internal graph coords. Draw in Gcur_ enclosed in a setbounds
573 % path. Unknown components of p cause the setbounds path to have width or
574 % height 1 instead of 0. Then Gupbb_ sets these components to 0 and Gpconv_
575 % supresses subsequent repositioning.
576 def Glab_(expr p)(suffix $)(text c) =
577 save sdim_; pair sdim_;
578 sdim_ := (if unknown xpart p: 1+ fi 0, if unknown ypart p: 1+ fi 0);
579 Gupbb_(p);
580 addto Gcur_ also
581 image(c(p); Gsetb_ p--p+sdim_--cycle) _op_
582 enddef;
583
584
585 % Stash the result drawing command c in the Ggl_ table using with list w and
586 % an index based on angle laboff$.
587 vardef Gglab_(suffix $)(text c) text w =
588 Ggl_[1.5+angle laboff$ /90] = image(c(origin) w);
589 enddef;
590
591
592 def Glloc_ primary p =
593 if pair p: Glab_(p)
594 elseif numeric p: Glab_(point p of pathpart Gdpic_)
595 else: Gglab_
596 fi
597 enddef;
598
599
600 % Place label p at user graph coords t using with list w. (t is a time, a pair
601 % or 2 numerics or strings).
602 vardef glabel@#(expr p)(text t) text w =
603 Glloc_ Gtcvi_(t) (@#,label@#(p)) w; enddef;
604
605
606 % Place label p at user graph coords t using with list w and draw a dot there.
607 % (t is a time, a pair, or 2 numerics or strings).
608 vardef gdotlabel@#(expr p)(text t) text w =
609 Glloc_ Gtcvi_(t) (@#,dotlabel@#(p)) w; enddef;
610
611
612 def OUT = enddef; % location text for outside labels
613
614
615
616 %%%%%%%%%%%%%%%%%%%%%%%%%% Grid lines, ticks, etc. %%%%%%%%%%%%%%%%%%%%%%%%%%
617
618 % Grid lines and tick marks are transformed versions of the templates below.
619 % In the template paths, (0,0) is on the edge of the frame and inward is to
620 % the right.
621 path Gtemplate.itick, Gtemplate.otick, Gtemplate.grid;
622 Gtemplate.itick = origin--(7bp,0);
623 Gtemplate.otick = (-7bp,0)--origin;
624 Gtemplate.grid = origin--(1,0);
625
626 vardef itick@#(expr f,u) text w = Gtlab_(@#,@,false,f,u,w); enddef;
627
628 vardef otick@#(expr f,u) text w = Gtlab_(@#,@,false,f,u,w); enddef;
629
630 vardef grid@#(expr f,u) text w = Gtlab_(@#,@,true,f,u,w); enddef;
631
632
633 % Produce a tick or grid mark for label suffix $, Gtemplate suffix $$,
634 % coordinate value u, and with list w. Boolean c tells whether Gtemplate$$
635 % needs scaling by X_.gdim or Y_.gdim, and f gives a format string or a label
636 % picture.
637 def Gtlab_(suffix $,$$)(expr c, f, u)(text w) =
638 Glab_(Gtcvi_(Ggpos_($,u)),,draw Ggpic_$($$,c,f,u,w) shifted)
639 enddef;
640
641
642 % Generate label positioning arguments appropriate for label suffix $ and
643 % coordinate u.
644 def Ggpos_(suffix $)(expr u) =
645 if xpart laboff.$=0: u,whatever else: whatever,u fi
646 enddef;
647
648
649 % Generate a picture of a grid line labeled with coordinate value u, picture
650 % or format string f, and with list w. Suffix @# is bot, top, lft, or rt,
651 % suffix $ identifies entries in the Gtemplate table, and boolean c tells
652 % whether to scale Gtemplate$.
653 vardef Ggpic_@#(suffix $)(expr c, f, u)(text w) =
654 if unknown u: Gerr_(u,"Label coordinate should be known"); nullpicture
655 else:
656 save p; path p;
657 interim warningcheck:=0;
658 Gneedgr_:=false;
659 p = Gtemplate$ zscaled -laboff@#
660 if c: Gxyscale fi
661 shifted (((.5 + laboff@# dotprod (.5,.5)) * laboff@#) Gxyscale);
662 image(draw p w;
663 label@#(if string f: format(f,u) else: f fi, point 0 of p))
664 fi
665 enddef;
666 def Gxyscale = xscaled X_.gdim yscaled Y_.gdim enddef;
667
668
669 % Draw the frame or the part corresponding to label suffix @# using with list w.
670 vardef frame@# text w =
671 Gneedfr_:=false;
672 picture p_;
673 p_ = image(draw
674 if str@#<>"": subpath round(angle laboff@#*Gfra_+Gfrb_) of fi
675 unitsquare Gxyscale w);
676 Glab_((whatever,whatever),,draw p_ shifted);
677 enddef;
678 pair Gfra_; Gfra_=(1,1)/90; % unitsquare subpath is linear in label angle
679 pair Gfrb_; Gfrb_=(.75,2.25);
680
681
682
683
684 %%%%%%%%%%%%%%%%%%%%%%%%%% Automatic grid selection %%%%%%%%%%%%%%%%%%%%%%%%%%
685
686 string Glmarks[]; % marking options per decade for logarithmic scales
687 string Gumarks; % mark spacing options per decade for linear scales
688 string Gemarks; % exponent spacing options for logarithmic scales
689 newinternal Gmarks, Gminlog;
690 Gmarks := 4; % minimum number marks generated by auto.x or auto.y
691 Gminlog := 3.0; % revert to uniform marks when largest/smallest < this
692
693 def Gfor(text t) = for i=t endfor enddef; % to shorten the mark templates below
694 Glmarks[1]="1,2,5";
695 Glmarks[2]="1,1.5,2,3,4,5,7";
696 Glmarks[3]="1Gfor(6upto10:,i/5)Gfor(5upto10:,i/2)Gfor(6upto9:,i)";
697 Glmarks[4]="1Gfor(11upto20:,i/10)Gfor(11upto25:,i/5)Gfor(11upto19:,i/2)";
698 Glmarks[5]="1Gfor(21upto40:,i/20)Gfor(21upto50:,i/10)Gfor(26upto49:,i/5)";
699 Gumarks="10,5,2"; % start with 10 and go down; a final `,1' is appended
700 Gemarks="20,10,5,2,1";
701
702
703 % Determine the X_ or Y_ bounds on the range to be covered by automatic grid
704 % marks. Suffix @# is X_ or Y_. The result is log or linear to specify the
705 % type of grid spacing to use. Bounds are returned in variables local to
706 % begingraph..endgraph: pairs Gmll_ and Gmhh_ are upper and lower bounds in
707 % `modified exponential form'. In modified exponential form, (x,y) means
708 % (x/1000)*10^y, where 1000<=abs x<10000.
709 vardef Gpick_@# =
710 interim warningcheck:=0;
711 save l, h;
712 Gsetp_;
713 if @#ctyp>0: (l,h) else: -(h,l) fi = (@#low, @#high);
714 if abs @#ctyp=log:
715 Gmll_ := Meform(Mabs l)+Gbias_;
716 Gmhh_ := Meform(Mabs h)+Gbias_;
717 if h-l >=mlog Gminlog: log else: linear fi
718 else:
719 Gmll_ := Meform(@#sc + Mlog l)+Gbias_;
720 Gmhh_ := Meform(@#sc + Mlog h)+Gbias_;
721 linear
722 fi
723 enddef;
724 pair Gbias_; Gbias_=(0,3);
725 pair Gmll_, Gmhh_;
726
727
728 % Scan Glmarks[k] and evaluate tokens t for each m where l<=m<=h.
729 def Gmsc_(expr k, l, h)(text t) =
730 for m=scantokens Glmarks[k]:
731 exitif m>h;
732 if m>=l: t fi
733 endfor
734 enddef;
735
736
737 % Scan Gmark[k] and evaluate tokens t for each m and e where m*10^e belongs
738 % between l and h (inclusive), where both l and h are in modified exponent form.
739 def Gmscan_(expr k, l, h)(text t) =
740 for e=ypart l upto ypart h:
741 Gmsc_(k, if e>ypart l: 1 else: xpart l/1000 fi,
742 if e<ypart h: 10 else: xpart h/1000 fi, t)
743 endfor
744 enddef;
745
746
747 % Select a k for which Gmscan_(k,...) gives enough marks.
748 vardef Gkpick_ =
749 save k;
750 k = 0;
751 forever:
752 exitif unknown Glmarks[k+1];
753 exitif 0 Gmscan_(incr k, Gmll_, Gmhh_, +1) >= Gmarks;
754 endfor
755 k
756 enddef;
757
758
759 % Try to select an exponent spacing from Gemarks. If successful, set @# and
760 % return true
761 vardef Gempick_@# =
762 numeric @#;
763 for e=scantokens Gemarks:
764 @# = e;
765 exitif floor(ypart Gmhh_/e)-floor(Gey_(Gmll_)/e) >= Gmarks;
766 numeric @#;
767 endfor
768 known @#
769 enddef;
770
771 vardef Gey_(expr p) = ypart p if xpart p=1000: -1 fi enddef;
772
773
774 % Compute the mark spacing d between xpart Gmll_ and xpart Gmhh_.
775 vardef Gipick_ =
776 interim warningcheck:=0;
777 save m, n, d;
778 m = Gmarks;
779 n = 1 for i=1 upto mlog(xpart Gmhh_-xpart Gmll_)/Mten - mlog m/(Mten-epsilon):
780 *10 endfor;
781 if n<=1000:
782 for x=scantokens Gumarks:
783 d = n*x;
784 exitif 0 Gigen_(d,+1)>=m;
785 numeric d;
786 endfor
787 fi
788 if known d: d else: n fi
789 enddef;
790
791
792 def Gigen_(expr d)(text t) =
793 for m = d*ceiling(xpart Gmll_/d) step d until xpart Gmhh_:
794 t
795 endfor
796 enddef;
797
798
799 % Evaluate tokens t for exponents e in multiples of d in the range determined
800 % by Gmll_ and Gmhh_.
801 def Gemgen_(expr d)(text t) =
802 for e = d*floor(Gey_(Gmll_)/d+1)
803 step d until d*floor(ypart Gmhh_/d): t
804 endfor
805 enddef;
806
807
808 % Adjust Gmll_ and Gmhh_ so their exponent parts match and they are in true
809 % exponent form ((x,y) means x*10^y). Return the new exponent.
810 vardef Gesame_ =
811 interim warningcheck := 0;
812 save e;
813 e+3 = if Gmll_=Gbias_: ypart Gmhh_
814 elseif Gmhh_=Gbias_: ypart Gmll_
815 else: max(ypart Gmll_, ypart Gmhh_) fi;
816 forsuffixes $=Gmll_, Gmhh_:
817 $ := (xpart $ for i=ypart $ upto e+2: /(10) endfor, e);
818 endfor
819 e
820 enddef;
821
822
823 % Assume e is an integer and either m=0 or 1<=abs(m)<10000. Find m*(10^e)
824 % and represent the result as a string if its absolute value would be at least
825 % 4096 or less than .1. It is OK to return 0 as a string or a numeric.
826 vardef Gpack_(expr m, e) =
827 if (e>3)or(e<-4):
828 decimal m & "e" & decimal e
829 elseif e>=0:
830 if abs m<infinity/Ten_to[e]:
831 m*Ten_to[e]
832 else: decimal m & "e" & decimal e
833 fi
834 else:
835 save x; x=m/Ten_to[-e];
836 if abs x>=.1: x else: decimal m & "e" & decimal e fi
837 fi
838 enddef;
839
840
841 def auto suffix $ =
842 hide(def Gcma_= hide(def Gcma_=,enddef) enddef)
843 if Gpick_.Gsuf_($)=log:
844 if Gempick_.Gme_: Gemgen_(Gme_, Gcma_ Gpack_(1,e))
845 else:
846 Gmscan_(Gkpick_, Gmll_, Gmhh_, Gcma_ Gpack_(m,e))
847 fi
848 else:
849 hide(Gme_:=Gesame_)
850 Gigen_(Gipick_, Gcma_ Gpack_(m,Gme_))
851 fi
852 enddef;
853
854
855 string Autoform; Autoform = "%g";
856
857 vardef autogrid(suffix tx, ty) text w =
858 Gneedgr_:=false;
859 if str tx<>"": for x=auto.x: tx(Autoform,x) w; endfor fi
860 if str ty<>"": for y=auto.y: ty(Autoform,y) w; endfor fi
861 enddef;
862
863
864
865 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% endgraph %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
866
867 def endgraph =
868 if Gneedgr_: autogrid(otick.bot, otick.lft); fi
869 if Gneedfr_: frame; fi
870 setcoords(linear,linear);
871 interim truecorners:=1;
872 for b=bbox Gfin_:
873 setbounds Gfin_ to b;
874 for i=0 step .5 until 3.5:
875 if known Ggl_[i]: addto Gfin_ also Ggl_[i] shifted point i of b; fi
876 endfor
877 endfor
878 Gfin_
879 endgroup
880 enddef;