Debian Codegraph @

texmf-dist/doc/metapost/base/source-manual/mpgraph.tex

raw
1 % $Id$
2 % MetaPost graph doc, by John Hobby. License at end.
3 \listfiles
4 \RequirePackage{ifpdf}
5 \ifpdf
6 \ifnum\pdftexversion<140
7 \else
8 \pdfminorversion=5
9 \pdfobjcompresslevel=1% Use compressed object streams.
10 \fi
11 \RequirePackage{cmap}
12 \fi
13 \documentclass{article} % article is NOT the original style
14 \usepackage[T1]{fontenc}
15 \usepackage{lmodern}
16 \usepackage{textcomp}
17 \usepackage{mflogo}
18 \usepackage{makeidx}
19 \usepackage{fancyvrb}
20 \usepackage{ctabbing}
21 \RecustomVerbatimEnvironment{verbatim}{BVerbatim}{baseline=c}
22 \usepackage{graphics}
23 \usepackage[textwidth=6in,textheight=8.65in]{geometry}
24 \usepackage{multicol}
25
26 \newcommand\descr[1]{{\langle\hbox{\rm#1}\rangle}}
27 \newcommand\invisgap{\nobreak\hskip0pt\relax}
28 \newcommand\tdescr[1]{$\langle$\invisgap{\rm#1}\invisgap$\rangle$}
29 \newcommand\Ignore[1]{} % For fooling delatex so spell will work
30
31 \newcommand\mathcenter[1]{\vcenter{\hbox{#1}}}
32
33 \author{John D. Hobby}
34 \title{Drawing Graphs with {MetaPost}}
35 \date{}
36
37
38 \newcommand\myabstract{%
39 This paper describes a graph-drawing package that has been implemented
40 as an extension to the MetaPost graphics language. MetaPost has
41 a powerful macro facility for implementing such extensions. There are
42 also some new language features that support the graph macros.
43 Existing features for generating and manipulating pictures
44 allow the user to do things that would be difficult to achieve
45 in a stand-alone graph package.}
46
47 \newcommand\mykeywords{%
48 typesetting; graphs; MetaPost}
49
50 \usepackage[rgb,x11names]{xcolor}% Optimize for screen reading.
51 \usepackage{hyperxmp}
52 \usepackage{hyperref}
53 \hypersetup{
54 pdftitle={Drawing Graphs with MetaPost},
55 pdfauthor={John D. Hobby and the MetaPost development team},
56 pdfkeywords={typesetting, graphs, MetaPost, TeX}
57 }
58 \hypersetup{
59 pdfstartview={XYZ null null null},% Zoom factor is determined by viewer.
60 colorlinks,
61 linkcolor=RoyalBlue3,
62 urlcolor=Chocolate4,
63 citecolor=SpringGreen3
64 }
65 \usepackage[all]{hypcap}
66 \ifpdf
67 \pdfmapfile{=cm2lm.map}% replace CM by LM in figures
68 \else
69 \DeclareGraphicsExtensions{.mps}
70 \DeclareGraphicsRule{mps}{eps}{*}{}
71 \usepackage{breakurl}
72 \fi
73
74
75 \begin{document}
76 \maketitle
77 \begin{abstract} \myabstract \end{abstract}
78 \ifx\keywords\undefined \else
79 \begin{keywords} \mykeywords \end{keywords}
80 \fi
81
82 \setlength{\columnsep}{2.5em}
83 \begin{multicols}{2}
84 \tableofcontents
85 \end{multicols}
86
87 \section{Introduction}
88 \label{intro}
89
90 MetaPost is a batch-oriented graphics language based on Knuth's \MF\footnote{\MF\
91 is a trademark of Addison Wesley Publishing Company.}, but with
92 PostScript\footnote{PostScript is a registered trademark of Adobe Systems Inc.}
93 output and numerous features for integrating text and graphics.
94 The author has tried to make this paper as independent as possible of the
95 user's manual~\cite{ho:mp3}, but fully appreciating all the material requires
96 some knowledge of the MetaPost language.
97
98 We concentrate on the mechanics of producing particular kinds of graphs
99 because the question of what type of graph is best in a given situation
100 is covered elsewhere; e.g., Cleveland~\cite{Cleve85,Cleve93,Cleve93a} and
101 Tufte~\cite{Tufte83}.
102 The goal is to provide at least the power of UNIX\footnote{UNIX is a registered
103 trademark of UNIX System Laboratories, Inc.} {\it
104 grap\/}~\cite{BenKer90}, but within the MetaPost language.
105 Hence the package is implemented using MetaPost's powerful macro facility.
106
107 The graph macros provide the following functionality:
108 \begin{enumerate}
109 \item Automatic scaling
110 \item Automatic generation and labeling of tick marks or grid lines
111 \item Multiple coordinate systems
112 \item Linear and logarithmic scales
113 \item Separate data files
114 \item Ability to handle numbers outside the usual range
115 \item Arbitrary plotting symbols
116 \item Drawing, filling, and labeling commands for graphs
117 \end{enumerate}
118 In addition to these items, the user also has access to all the features
119 described in the MetaPost user's manual~\cite{ho:mp3}.
120 These include access to almost all the features of PostScript,
121 ability to use and manipulate typeset text,
122 ability to solve linear equations,
123 and data types for points, curves, pictures, and coordinate transformations.
124
125 Section~\ref{grmac} describes the graph macros from a user's perspective
126 and presents several examples. Sections \ref{nummac} and~\ref{formsec} discuss
127 auxiliary packages for manipulating and typesetting numbers and Section~\ref{concl}
128 gives some concluding remarks. Appendix~\ref{summsec} summarizes the graph-drawing
129 macros.
130
131
132 \section{Using the Graph Macros}
133 \label{grmac}
134
135 A MetaPost input file that uses the graph macros should begin with
136 $$ \hbox{\tt input graph} $$
137 This reads a macro file {\tt graph.mp} and defines the graph-drawing commands
138 explained below. The rest of the file should be one or more instances of
139 $$ \vbox{\hbox{\tt beginfig($\descr{figure number}$);}
140 \hbox{\tt $\descr{graphics commands}$ endfig;}}
141 $$
142 followed by {\tt end}.
143
144 The following \tdescr{graphics commands} suffice to generate the graph in
145 Figure~\ref{fig1} from the data file {\tt agepop91.d}:
146 $$\begin{verbatim}
147 draw begingraph(3in,2in);
148 gdraw "agepop91.d";
149 endgraph;
150 \end{verbatim}
151 $$
152 (Each line of {\tt agepop91.d} gives an age followed the estimated number of
153 Americans of that age in 1991 \cite{Census92}.)
154
155 \begin{figure}[htp]
156 $$ \includegraphics{mpgraph-1.mps} $$
157 \caption{A graph of the 1991 age distribution in the United States}
158 \label{fig1}
159 \end{figure}
160
161 \subsection{Basic Graph-Drawing Commands}
162
163 % begingraph, endgraph, gdraw
164
165 All graphs should begin with
166 $$ \hbox{\tt begingraph($\descr{width}$,$\descr{height}$);} $$
167 and end with {\tt endgraph}. This is syntactically a \tdescr{picture expression},
168 so it should be preceded by {\tt draw} and followed by a semicolon as in the
169 example.\footnote{See the User's Manual~\cite{ho:mp3} for explanations of {\tt draw}
170 commands and syntactic elements like \tdescr{picture expression}.}
171 The \tdescr{width} and \tdescr{height} give the dimensions of the
172 graph itself without the axis labels.
173
174 The command
175 $$ {\tt gdraw}\ \descr{expression}\ \descr{option list} $$
176 draws a graph line. If the \tdescr{expression} is of type string, it names a data
177 file; otherwise it is a path that gives the function to draw. The
178 \tdescr{option list} is zero or more drawing options
179 $$ {\tt withpen} \descr{pen expression}
180 \mid {\tt withcolor} \descr{color expression}
181 \mid {\tt dashed} \descr{picture expression}
182 $$
183 that give the line width, color, or dash pattern as explained in the User's
184 Manual~\cite{ho:mp3}.
185
186 % plot <picture>
187
188 In addition to the standard drawing options, the \tdescr{option list} in a
189 {\tt gdraw} statement can contain
190 $$ {\tt plot}\ \descr{picture expression} $$
191 The \tdescr{picture expression} gives a plotting symbol to be drawn at each
192 path knot. The {\tt plot} option suppresses line drawing so that%
193 \footnote{Troff users should replace {\tt btex \$\string\bullet\$ etex} with
194 {\tt btex \string\(bu etex}.}
195 \Ignore{\)}% Help delatex so spell will work
196 $$ \hbox{\verb|gdraw "agepop91.d" plot btex $\bullet$ etex|} $$
197 generates only bullets as shown in Figure~\ref{fig2}.
198 (Following the {\tt plot} option with a {\tt withpen} option would
199 cause the line to reappear superimposed on the plotting symbols.)
200
201 \begin{figure}[htp]
202 $$ \includegraphics{mpgraph-2.mps} $$
203 \caption{The 1991 age distribution plotted with bullets}
204 \label{fig2}
205 \end{figure}
206
207 Watch out for the following: the \tdescr{picture expression} is placed
208 with the lower-left corner at the path knot, not its center. If you
209 want it to be dead-center, you have to correct the placement
210 yourself. For the example above, you need something like this instead:
211
212 \medskip
213 \begin{verbatim}
214 def MPbullet =
215 btex \lower\fontdimen22\cmsy \hbox to 0pt{\hss\cmsy\char15\hss} etex
216 enddef;
217 \end{verbatim}
218
219 \medskip\noindent
220 followed by:
221 $$ \hbox{\verb|gdraw "agepop91.d" plot MPbullet|} $$
222
223
224 % glabel, gdotlabel, OUT
225
226 The {\tt glabel} and {\tt gdotlabel} commands add labels to a graph. The
227 syntax for {\tt glabel} is
228 $$ {\tt glabel.}\ \descr{label suffix}
229 \hbox{\tt ($\descr{string or picture expression}$, $\descr{location}$)}
230 \ \descr{option list}
231 $$
232 where \tdescr{location} identifies the location being labeled and
233 \tdescr{label suffix} tells how the label is offset relative to that location.
234 The {\tt gdotlabel} command is identical, except it marks the location with a
235 dot. A \tdescr{label suffix} is as in plain MetaPost:
236 \tdescr{empty} centers the label on the location;
237 {\tt lft}, {\tt rt}, {\tt top}, {\tt bot} offset the label horizontally or
238 vertically; and {\tt ulft}, {\tt urt}, {\tt llft}, {\tt lrt} give diagonal
239 offsets. The \tdescr{location} can be a pair of graph coordinates, a knot
240 number on the last {\tt gdraw} path, or the special location {\tt OUT}.
241 Thus
242 $$ \hbox{\verb|gdotlabel.top(btex $(50,0)$ etex, 50,0)|} $$
243 would put a dot at graph coordinates {\tt(50,0)} and place the typeset text
244 ``$(50,0)$'' above it. Alternatively,
245 $$ \hbox{\verb|glabel.ulft("Knot3", 3)|} $$
246 typesets the string {\tt "Knot3"} and places it above and to the left of
247 Knot~3 of the last {\tt gdraw} path. (The knot number 3 the path's ``time''
248 parameter~\cite[Section 8.2]{ho:mp3}.)
249
250 The \tdescr{location} {\tt OUT} places a label relative to the whole graph.
251 For example, replacing ``{\tt gdraw "agepop91.d"}'' with
252 $$\begin{verbatim}
253 glabel.lft(btex \vbox{\hbox{Population} \hbox{in millions}} etex, OUT);
254 glabel.bot(btex Age in years etex, OUT);
255 gdraw "agepopm.d";
256 \end{verbatim}
257 $$
258 in the input for Figure~\ref{fig1} generates Figure~\ref{fig3}.
259 This improves the graph by adding axis labels and using a new data file
260 {\tt agepopm.d} where the populations have been divided by one million to avoid
261 large numbers. We shall see later that simple transformations such as this can
262 be achieved without generating new data files.
263
264 \begin{figure}[htp]
265 $$ \includegraphics{mpgraph-3.mps} $$
266 \caption{An improved version of the 1991 age distribution graph}
267 \label{fig3}
268 \end{figure}
269
270 All flavors of \TeX\ can handle multi-line labels via the \verb|\hbox| within
271 \verb|\vbox| arrangement used above, but \LaTeX\ users will find it more natural
272 to use the {\tt tabular} environment~\cite{LaTeXman}.
273 Troff user's can use nofill mode:
274 $$\begin{verbatim}
275 btex .nf
276 Population
277 in millions etex
278 \end{verbatim}
279 $$
280
281
282 \subsection{Coordinate Systems}
283 \label{coords}
284
285 The graph macros automatically shift and rescale coordinates from data files,
286 {\tt gdraw} paths, and {\tt glabel} locations to fit the graph. Whether the
287 range of $y$~coordinates is 0.64 to 4.6 or 640,000 to 4,600,000, they
288 get scaled to fill about 88\% of the height specified in the {\tt begingraph}
289 statement. Of course line widths, labels, and plotting symbols are not
290 rescaled.
291
292 % setrange
293
294 The {\tt setrange} command controls the shifting and rescaling process by
295 specifying the minimum and maximum graph coordinates:
296 $$ \hbox{\tt setrange($\descr{coordinates}$,\,$\descr{coordinates}$)} $$
297 where
298 \begin{ctabbing}
299 $\tt \descr{coordinates} \rightarrow \descr{pair expression}$\\
300 $\tt \qquad \;|\; \descr{numeric or string expression}\hbox{\tt ,}
301 \descr{numeric or string expression}$
302 \end{ctabbing}
303 The first \tdescr{coordinates} give $(x_{\rm min},y_{\rm min})$ and the second give
304 $(x_{\rm max},y_{\rm max})$. The lines $x=x_{\rm min}$, $x=x_{\rm max}$,
305 $y=y_{\rm min}$, and $y=y_{\rm max}$ define the rectangular frame around the graph
306 in Figures \ref{fig1}--\ref{fig3}. For example, an adding a statement
307 $$ \hbox{\tt setrange(origin, whatever,\,whatever)} $$
308 to the input for Figure~\ref{fig3} yields Figure~\ref{fig4}.
309 The first \tdescr{coordinates} are given by the predefined pair constant
310 {\tt origin}, and the other coordinates are left unspecified. Any unknown
311 value would work as well, but {\tt whatever} is the standard MetaPost
312 representation for an anonymous unknown value.
313
314 \begin{figure}[htp]
315 $$ \begin{verbatim}
316 draw begingraph(3in,2in);
317 glabel.lft(btex \vbox{\hbox{Population} \hbox{in millions}} etex, OUT);
318 glabel.bot(btex Age in years etex, OUT);
319 setrange(origin, whatever,whatever);
320 gdraw "agepopm.d";
321 endgraph;
322 \end{verbatim}
323 \atop
324 \includegraphics{mpgraph-4.mps}
325 $$
326 \caption{The 1991 age distribution graph and the input that creates it.}
327 \label{fig4}
328 \end{figure}
329
330 % strings for big coordinates
331
332 Notice that the syntax for {\tt setrange} allows coordinate values to be given
333 as strings. Many commands in the graph package allow this option. It is
334 provided because the MetaPost language uses fixed point numbers that must be
335 less than 32768. This limitation is not as serious as it sounds because good
336 graph design dictates that coordinate values should be ``of reasonable
337 magnitude''~\cite{Cleve85,Tufte83}. If you really want $x$ and $y$
338 to range from 0 to 1,000,000,
339 $$ \hbox{\tt setrange(origin, "1e6",\,"1e6")} $$
340 does the job. Any fixed or floating point representation is acceptable
341 as long as the exponent is introduced by the letter ``{\tt e}''.
342
343 % setcoords
344
345 Coordinate systems need not be linear. The {\tt setcoords} command allows
346 either or both axes to have logarithmic spacing:
347 \begin{ctabbing}
348 $\tt \descr{coordinate setting} \rightarrow setcoords\hbox{\tt (}
349 \descr{coordinate type}\hbox{\tt ,}\,\descr{coordinate type}\hbox{\tt )}$\\
350 $\tt \descr{coordinate type} \rightarrow
351 log \;|\; linear \;|\; \hbox{\tt -}log \;|\; \hbox{\tt -}linear$
352 \end{ctabbing}
353 A negative \tdescr{coordinate type} makes $x$ (or $y$) run backwards so it is
354 largest on the left side (or bottom) of the graph.
355
356 Figure~\ref{fig5} graphs execution times for two matrix multiplication algorithms
357 using
358 $$ \hbox{\tt setcoords(log,log)} $$
359 to specify logarithmic spacing on both axes. The data file {\tt matmul.d} gives
360 timings for both algorithms:
361 $$ \hbox to\hsize{\footnotesize\hfil$
362 \begin{verbatim}
363 20 .007861 standard MM: size, seconds
364 30 .022051
365 40 .050391
366 60 .15922
367 80 .4031
368 120 1.53
369 160 3.915
370 240 18.55
371 320 78.28
372 480 279.24
373
374 20 .006611 Strassen: size, seconds
375 30 .020820
376 40 .049219
377 60 .163281
378 80 .3975
379 120 1.3125
380 160 3.04
381 240 9.95
382 320 22.17
383 480 72.60
384 \end{verbatim}
385 \hfil$}
386 $$
387 A blank line in a data file ends a data set. Subsequent {\tt gdraw} commands
388 access additional data sets by just naming the same data file again.
389 Since each line gives one $x$~coordinate and one $y$~coordinate, commentary
390 material after the second data field on a line is ignored.
391
392 \begin{figure}[htp]
393 $$ \mathcenter{\includegraphics{mpgraph-5.mps}}
394 \quad
395 \begin{BVerbatim}[baseline=c]
396 draw begingraph(2.3in,2in);
397 setcoords(log,log);
398 glabel.lft(btex Seconds etex,OUT);
399 glabel.bot(btex Matrix size etex,
400 OUT);
401 gdraw "matmul.d" dashed evenly;
402 glabel.ulft(btex Standard etex,8);
403 gdraw "matmul.d";
404 glabel.lrt(btex Strassen etex,7);
405 endgraph;
406 \end{BVerbatim}
407 $$
408 \caption{Timings for two matrix multiplication algorithms with the corresponding
409 MetaPost input.}
410 \label{fig5}
411 \end{figure}
412
413 Placing a {\tt setcoords} command between two {\tt gdraw} commands graphs two
414 functions in different coordinate systems as shown in Figure~\ref{fig6}.
415 Whenever you give a {\tt setcoords} command, the interpreter examines what has
416 been drawn, selects appropriate $x$ and $y$ ranges, and scales everything to
417 fit. Everything drawn afterward is in a new coordinate system that need not
418 have anything in common with the old coordinates unless {\tt setrange} commands
419 enforce similar coordinate ranges. For instance, the two {\tt setrange}
420 commands force both coordinate systems to have $x$ ranging from 80 to~90 and
421 $y$~starting at 0.
422
423 \begin{figure}[htp]
424 $$ \begin{verbatim}
425 draw begingraph(6.5cm,4.5cm);
426 setrange(80,0, 90,whatever);
427 glabel.bot(btex Year etex, OUT);
428 glabel.lft(btex \vbox{\hbox{Emissions in} \hbox{thousands of}
429 \hbox{metric tons} \hbox{(heavy line)}}etex, OUT);
430 gdraw "lead.d" withpen pencircle scaled 1.5pt;
431 autogrid(,otick.lft);
432 setcoords(linear,linear);
433 setrange(80,0, 90,whatever);
434 glabel.rt(btex \vbox{\hbox{Micrograms} \hbox{per cubic}
435 \hbox{meter of air} \hbox{(thin line)}}etex, OUT);
436 gdraw "lead.d";
437 autogrid(otick.bot,otick.rt);
438 endgraph;
439 \end{verbatim}
440 \atop
441 \mathcenter{\includegraphics{mpgraph-6.mps}}
442 $$
443 \caption{Annual lead emissions and average level at atmospheric monitoring
444 stations in the United States. The MetaPost input is shown above
445 the graph.}
446 \label{fig6}
447 \end{figure}
448
449 % autogrid
450
451 When you use multiple coordinate systems, you have to specify where the axis
452 labels go. The default is to put tick marks on the bottom and the left side of
453 the frame using the coordinate system in effect when the {\tt endgraph} command
454 is interpreted. Figure~\ref{fig6} uses the
455 $$ \hbox{\tt autogrid(,otick.lft)} $$
456 to label the left side of the graph with the $y$~coordinates in effect before
457 the {\tt setcoords} command. This suppresses the default axis labels, so another
458 {\tt autogrid} command is needed to label the bottom and right sides of the
459 graph using the new coordinate system. The general syntax is
460 $$ \hbox{$\tt autogrid\hbox{\tt (}\descr{axis label command}\hbox{\tt ,}\,
461 \descr{axis label command}\hbox{\tt )}\ \descr{option list}$}
462 $$
463 where
464 \begin{ctabbing}
465 $\tt \descr{axis label command} \rightarrow \descr{empty}
466 \;|\; \descr{grid or tick}\, \descr{label suffix}$\\
467 $\tt \descr{grid or tick} \rightarrow grid \;|\; itick \;|\; otick$
468 \end{ctabbing}
469 The \tdescr{label suffix} should be {\tt lft}, {\tt rt}, {\tt top},
470 or {\tt bot}.
471
472 The first argument to {\tt autogrid} tells how to label the $x$~axis and the
473 second argument does the same for~$y$. An \tdescr{empty} argument suppresses
474 labeling for that axis. Otherwise, the \tdescr{label suffix} tells which side
475 of the graph gets the numeric label. Be careful to use {\tt bot} or {\tt top}
476 for the $x$~axis and {\tt lft} or {\tt rt} for the $y$~axis. Use {\tt otick}
477 for outward tick marks, {\tt itick} for inward tick marks, and {\tt grid} for
478 grid lines. The \tdescr{option list} tells how to draw the tick marks or grid
479 lines. Grid lines tend to be a little overpowering, so it is a good idea to
480 give a {\tt withcolor} option to make them light gray so they do not make the
481 graph too busy.
482
483
484 \subsection{Explicit Grids and Framing}
485
486 % otick, itick, grid, (format)
487
488 In case {\tt autogrid} is not flexible enough, axis label commands generate
489 grid lines or tick marks one at a time. The syntax is
490 $$ \descr{grid or tick}\hbox{\tt .}\descr{label suffix}
491 \hbox{\tt ($\descr{label format}$,\,$\descr{numeric or string expression}$)}
492 \ \descr{option list}
493 $$
494 where \tdescr{grid or tick} and \tdescr{label suffix} are as in {\tt autogrid},
495 and \tdescr{label format} is either a format string like \verb|"%g"| or a
496 picture containing the typeset numeric label.
497
498 The axis label commands use a macro
499 $$ \hbox{\tt format($
500 \descr{format string}$,\,$\descr{numeric or string expression}$)}
501 $$
502 to typeset numeric labels. Full details appear in Section~\ref{formsec},
503 but when the \tdescr{format string} is \verb|"%g"|, it uses decimal notation
504 unless the number is large enough or small enough to require scientific notation.
505
506 The example in Figure~\ref{fig7} invokes
507 $$ \hbox{\verb|format("%g",y)|} $$
508 explicitly so that grid lines can be placed at transformed coordinates.
509 It defines the transformation ${\tt newy}(y)=y/75+\ln y$ and shows that
510 this function increases almost linearly.\footnote{The manual~\cite{ho:mp3}
511 explains how {\tt vardef} defines functions and {\tt mlog} computes logarithms.}
512 This is a little like using logarithmic $y$-coordinates, except that $y$ is
513 mapped to $y/75+\ln y$ instead of just $\ln y$.
514
515 \begin{figure}[htp]
516 $$ \begin{verbatim}
517 vardef newy(expr y) = (256/75)*y + mlog y enddef;
518 draw begingraph(3in,2in);
519 glabel.lft(btex \vbox{\hbox{Population} \hbox{in millions}} etex, OUT);
520 path p;
521 gdata("timepop.d", $, augment.p($1, newy(Scvnum $2)); );
522 gdraw p withpen nullpen;
523 for y=5,10,20,50,100,150,200,250:
524 grid.lft(format("%g",y), newy(y)) withcolor .85white;
525 endfor
526 autogrid(grid.bot,) withcolor .85white;
527 gdraw p;
528 frame.llft;
529 endgraph;
530 \end{verbatim}
531 \atop
532 \includegraphics{mpgraph-7.mps}
533 $$
534 \caption{Population of the United States in millions versus time with the
535 population re-expressed as $p/75+\ln p$. The MetaPost input shown
536 above the graph assumes a data file {\tt ttimepop.d} that gives
537 (year, $p/75+\ln p$) pairs.}
538 \label{fig7}
539 \end{figure}
540
541 % frame
542
543 Figure~\ref{fig7} uses the command
544 $$ \hbox{\tt frame.} \descr{label suffix}\ \descr{option list} $$
545 to draw a special frame around the graph. In this case the \tdescr{label suffix}
546 is {\tt llft} to draw just the bottom and left sides of the frame. Suffixes
547 {\tt lrt}, {\tt ulft}, and {\tt urt} draw other combinations of two sides;
548 suffixes {\tt lft}, {\tt rt}, {\tt top}, {\tt bot} draw one side, and \tdescr{empty}
549 draws the whole frame. For example
550 $$ \hbox{\verb|frame dashed evenly|} $$
551 draws all four sides with dashed lines. The default four-sided frame is drawn
552 only when there is no explicit {\tt frame} command.
553
554 % auto, (sarith.mp)
555
556 To label an axis as {\tt autogrid} does but with the labels transformed
557 somehow, use
558 $$ \hbox{{\tt auto.x}\quad or\quad {\tt auto.y}} $$
559 for positioning tick marks or grid lines. These macros produce comma-separated
560 lists for use in {\tt for} loops. Any $x$ or $y$ values in these lists that
561 cannot be represented accurately within MetaPost's fixed-point number system
562 are given as strings. A standard macro package that is loaded via
563 $$ \hbox{\tt input sarith} $$
564 defines arithmetic operators that work on numbers or strings. Binary operators
565 {\tt Sadd}, {\tt Ssub}, {\tt Smul}, and {\tt Sdiv} do addition, subtraction
566 multiplication, and division.
567
568 One possible application is rescaling data.
569 Figure~\ref{fig4} used a special data file {\tt agepopm.d} that had $y$~values
570 divided by one million. This could be avoided by replacing
571 ``{\tt gdraw "agepopm.d"}'' by
572 $$\begin{verbatim}
573 gdraw "agepop91.d";
574 for u=auto.y: otick.lft(format("%g",u Sdiv "1e6"), u); endfor
575 autogrid(otick.bot,)
576 \end{verbatim}
577 $$
578
579
580 \subsection{Processing Data Files}
581 \label{dfilesec}
582
583 % gdata
584
585 The most general tool for processing data files is the {\tt gdata} command:
586 $$ \hbox{\tt gdata(} \descr{string expression} \hbox{\tt,}\, \descr{variable}
587 \hbox{\tt,}\, \descr{commands} \hbox{\tt )}
588 $$
589 It takes a file name, a variable~$v$, and a list of commands to be executed for
590 each line of the data file. The commands are executed with {\tt i} set to the
591 input line number and strings $v${\tt 1}, $v${\tt 2}, $v${\tt 3}, \ldots\ set
592 to the input fields on the current line. A null string marks the end of the
593 $v$ array.
594
595 Using a {\tt glabel} command inside of {\tt gdata} generates a scatter plot
596 as shown in Figure~\ref{fig8}. The data file {\tt countries.d} begins
597 $$\begin{verbatim}
598 20.910 75.7 US
599 1.831 66.7 Alg
600 \end{verbatim}
601 $$
602 where the last field in each line gives the label to be plotted. Setting
603 {\tt defaultfont} in the first line of input selects a small font for these
604 labels. Without these labels, no {\tt gdata} command would be needed.
605 Replacing the {\tt gdata} command with
606 $$ \hbox{\verb|gdraw "countries.d" plot btex$\circ$etex|} $$
607 would change the abbreviated country names to open circles.
608
609 \begin{figure}[htp]
610 $$\begin{verbatim}
611 defaultfont:="cmr7";
612 draw begingraph(3in,2in);
613 glabel.lft(btex \vbox{\hbox{Life}\hbox{expectancy}} etex, OUT);
614 glabel.bot(btex Per capita G.N.P. (thousands of dollars) etex, OUT);
615 setcoords(log,linear);
616 gdata("countries.d", s,
617 glabel(s3, s1, s2);
618 )
619 endgraph;
620 \end{verbatim}
621 \atop
622 \includegraphics{mpgraph-8.mps}
623 $$
624 \caption{A scatter plot and the commands that generated it}
625 \label{fig8}
626 \end{figure}
627
628 Both {\tt gdraw} and {\tt gdata} ignore an optional initial `\%' on each input
629 line, parse data fields separated by white space, and stop if they encounter an
630 input line with no data fields. Leading percent signs make graph data
631 look like MetaPost comments so that numeric data can be placed at the beginning
632 of a MetaPost input file.
633
634 % augment
635
636 It is often useful to construct one or more paths when reading a data file
637 with {\tt gdata}. The {\tt augment} command is designed for this:
638 $$ \hbox{\tt augment.} \descr{path variable} \hbox{\tt(}\descr{coordinates}\hbox{\tt)}
639 $$
640 If the path variable does not have a known value, it becomes a path of length
641 zero at the given coordinates; otherwise a line segment to the given coordinates
642 is appended to the path. The \tdescr{coordinates} may be a pair expression or
643 any combination of strings and numerics as explained at the beginning of
644 Section~\ref{coords}.
645
646 If a file {\tt timepop.d} gives $t$,~$p$ pairs, {\tt augment} can be used like
647 this to graph {\tt newy(}$p${\tt)} versus~$t$:
648 $$\begin{verbatim}
649 path p;
650 gdata("timepop.d", s, augment.p(s1, newy(scantokens s2)); );
651 gdraw p;
652 \end{verbatim}
653 $$
654 (MetaPost's {\tt scantokens} primitive interprets a string as if it were the
655 contents of an input file. This finds the numeric value of data field
656 {\tt s2}.)
657
658 % gfill (energy.d)
659
660 Figure~\ref{fig9} shows how to use {\tt augment} to read multiple column data
661 and make multiple paths. Paths {\tt p2}, {\tt p3}, {\tt p4}, {\tt p5} give
662 cumulative totals for columns 2 through 5 and pictures {\tt lab2} through
663 {\tt lab5} give corresponding labels. The expression
664 $$ \hbox{\verb|image(unfill bbox lab[j]; draw lab[j])|} $$
665 executes the given drawing commands and returns the resulting picture:
666 ``{\tt unfill bbox lab[j]}'' puts down a white background and ``{\tt draw
667 lab[j]}'' puts the label on the background.
668 The {\tt gfill} command is just like {\tt gdraw}, except it takes a cyclic
669 path and fills the interior with a solid color. The color is black unless
670 a {\tt withcolor} clause specifies another color.
671 See the manual~\cite{ho:mp3} for
672 explanations of {\tt for} loops, arrays, colors, and path construction
673 operators like \verb|--|, {\tt cycle}, and {\tt reverse}.
674
675 \begin{figure}[htp]
676 $$\begin{verbatim}
677 draw begingraph(3in,2in);
678 glabel.lft(btex \vbox{\hbox{Quadrillions}\hbox{of BTU}} etex, OUT);
679 path p[];
680 numeric t;
681 gdata("energy.d", $,
682 t:=0; augment.p1($1,0);
683 for j=2 upto 5:
684 t:=t+scantokens $[j]; augment.p[j]($1,t);
685 endfor)
686 picture lab[];
687 lab2=btex coal etex; lab3=btex crude oil etex;
688 lab4=btex natural gas etex; lab5=btex hydroelectric etex;
689 for j=5 downto 2:
690 gfill p[j]--reverse p[j-1]--cycle withcolor .16j*white;
691 glabel.lft(image(unfill bbox lab[j]; draw lab[j]), .7+length p[j]);
692 endfor
693 endgraph;
694 \end{verbatim}
695 \atop
696 \includegraphics{mpgraph-9.mps}
697 $$
698 \caption{A graph of U.S. annual energy production
699 and the commands that generated it}
700 \label{fig9}
701 \end{figure}
702
703
704 \section{Manipulating Big Numbers}
705 \label{nummac}
706
707 MetaPost inherits a fixed-point number system from Knuth's \MF~\cite{kn:d}.
708 Numbers are expressed in multiples of $2^{-16}$ and they must have absolute
709 value less than 32768. Knuth chose this system because it is perfectly adequate
710 for font design, and it guaranteed to give identical results on all types of
711 computers. Fixed-point numbers are seldom a problem in MetaPost because all
712 computations are based on coordinates that are limited by the size the paper on
713 which the output is to be printed. This does not hold for the input data in a
714 graph-drawing application. Although graphs look best when coordinate axes are
715 labeled with numbers of reasonable magnitude, the strict limits of fixed-point
716 arithmetic would be inconvenient.
717
718 % Sadd, Ssub, Smul, Sdiv
719
720 A simple way to handle large numbers is to include the line
721 $$ \hbox{\tt input sarith} $$
722 and then use binary operators {\tt Sadd}, {\tt Ssub}, {\tt Smul}, and {\tt Sdiv}
723 in place of \verb|+|, \verb|-|, \verb|*|, and \verb|/|. These operators are
724 inefficient but very flexible. They accept numbers or strings and return
725 strings in exponential notation with the exponent marked by ``{\tt e}'';
726 e.g., \verb|"6.7e-11"| means $6.7\times10^{-11}$.
727
728 % Sabs, Sleq, Sneq
729
730 The unary operator\footnote{The argument to a unary operator need not be
731 parenthesized unless it is an expression involving binary operators.}
732 $$ {\tt Sabs}\ \descr{string} $$
733 finds a string the represents the absolute value. Binary operators {\tt Sleq}
734 and {\tt Sneq} perform numeric comparisons on strings and return boolean
735 results.
736
737 % Scvnum
738
739 The operation
740 $$ {\tt Scvnum}\ \descr{string} $$
741 finds the numeric value for a string if this can be done without overflowing
742 MetaPost's fixed-point number system. If the string does not contain
743 ``{\tt e}'', it is much more efficient to use the primitive operation
744 $$ {\tt scantokens}\ \descr{string} $$
745
746 % Mten
747
748 The above operators are based on a low-level package that manipulates numbers
749 in ``{\tt Mlog} form.'' A number $x$ in {\tt Mlog} form represents
750 $$ \mu^{2^{16}x}, \quad {\rm where\ } \mu=-e^{2^{-24}}. $$
751 Any value between $1.61\times10^{-28}$ and $3.88\times10^{55}$ can be
752 represented this way. (There is a constant {\tt Mten} such that $k*{\tt Mten}$
753 represents $10^k$ for any integer~$k$ in the interval $[-29,55]$.)
754
755 % Mreadpath, Gpaths
756
757 The main reason for mentioning {\tt Mlog} form is that it allows graph data
758 to be manipulated as a MetaPost path. The function
759 $$ \hbox{\tt Mreadpath($\descr{file name}$)} $$
760 reads a data file and returns a path where all the coordinates are in
761 {\tt Mlog} form. An internal variable {\tt Gpaths} determines whether
762 {\tt gdraw} and {\tt gfill} expect paths to be given in {\tt Mlog} form.
763 For example, this graphs the data in {\tt agepop91.d} with $y$ coordinates
764 divided by one million:
765 $$\begin{verbatim}
766 interim Gpaths:=log;
767 gdraw Mreadpath("agepop91.d") shifted (0,-6*Mten);
768 \end{verbatim}
769 $$
770
771
772 \section{Typesetting Numbers}
773 \label{formsec}
774
775 % format
776
777 The graph package needs to compute axis labels and then typeset them.
778 The macro
779 $$ \hbox{\tt format($\descr{string expression}$,\,%
780 $\descr{numeric or string expression}$)} $$
781 does this. You must first {\tt input graph} or {\tt input format} to load the
782 macro file. The macro takes a format string and a number to typeset and returns
783 a picture containing the typeset result. Thus
784 $$ \hbox{\verb|format("%g",2+2)|}\quad {\rm yields}\quad \includegraphics{mpgraph-10.mps} $$
785 and
786 $$ \hbox{\verb|format("%3g","6.022e23")|}
787 \quad {\rm yields}\quad \includegraphics{mpgraph-11.mps}
788 $$
789
790 A format string consists of
791 \begin{itemize}
792 \item an optional initial string not containing a percent sign,
793 \item a percent sign,
794 \item an optional numeric precision $p$,
795 \item one of the conversion letters {\tt e}, {\tt f}, {\tt g}, {\tt G},
796 \item an optional final string $\beta$.
797 \end{itemize}
798 The initial and final strings are typeset in the default font (usually
799 {\tt cmr10}), and the typeset number is placed between them. For the {\tt e}
800 and {\tt g} formats, the precision~$p$ is the number of significant digits
801 allowed after rounding; for {\tt f} and {\tt G}, the number is rounded to the
802 nearest multiple of $10^{-p}$. If the precision is not specified, the default
803 is $p=3$. The {\tt e} format always uses scientific
804 notation and the {\tt f} format uses ordinary decimal notation but reverts to
805 scientific notation if the number is at least 10000. The {\tt g} and {\tt G}
806 formats also revert to scientific notation for non-zero numbers of magnitude
807 less than 0.001.
808
809 % init_numbers
810
811 The {\tt format} macro needs a set of templates to determine what font to use,
812 how to position the exponent, etc. The templates are normally initialized
813 automatically, but it is possible to set them explicitly by passing five picture
814 expressions to {\tt init\_numbers}. For instance, the default definition for
815 \TeX\ users is
816 $$\begin{verbatim}
817 init_numbers(btex$-$etex, btex$1$etex, btex${\times}10$etex,
818 btex${}^-$etex, btex${}^2$etex)
819 \end{verbatim}
820 $$
821 The first argument tells how to typeset a leading minus sign;
822 the second argument is an example of a 1-digit mantissa;
823 third comes whatever to put after the mantissa in scientific notation;
824 next come a leading minus sign for the exponent and a sample 1-digit exponent.
825
826 % Fe_plus, Fe_base
827
828 Picture variable \verb|Fe_plus| gives a leading plus sign for positive numbers,
829 and \verb|Fe_base| gives whatever should precede the exponent when typesetting
830 a power of ten. Calling \verb|init_numbers| initializes \verb|Fe_plus| to an
831 empty picture and constructs \verb|Fe_base| from its second and third arguments.
832
833
834
835 \section{Conclusion}
836 \label{concl}
837
838 The graph package makes it convenient to generate graphs from within the MetaPost
839 language. The primary benefits are the power of the MetaPost language and its
840 ability to interact with \TeX\ or troff for typesetting labels. Typeset labels
841 can be stored in picture variables and manipulated in various ways such measuring
842 the bounding box and providing a white background.
843
844 We have seen how to generate shaded regions and control line width, color, and
845 styles of dashed lines. Numerous other variations are possible.
846 The full MetaPost language~\cite{ho:mp3} provides many other potentially useful
847 features. It also has enough computing power to be useful for generating and
848 processing data.
849
850
851
852 \appendix
853 \section{Summary of the Graph Package}
854 \label{summsec}
855
856 % Not described elsewhere: gdrawarrow, gdrawdblarrow, Gmarks, Gminlog, Autoform
857
858 In the following descriptions, italic letters such as $w$ and $h$ denote
859 expression parameters and words in angle brackets denote other syntactic
860 elements. Unless specified otherwise, expression parameters can be either
861 numerics or strings. An \tdescr{option list} is a list of drawing options such
862 as {\tt withcolor .5white} or {\tt dashed evenly};
863 a \tdescr{label suffix} is one of {\tt lft}, {\tt rt}, {\tt top}, {\tt bot},
864 {\tt ulft}, {\tt urt}, {\tt llft}, {\tt lrt}.
865
866 \subsection{Graph Administration}
867
868 \begin{description}
869 \item[{\tt begingraph($w$,$h$)}]
870 Begin a new graph with the frame width and height given by numeric
871 parameters $w$ and $h$.
872 \item[{\tt endgraph}]
873 End a graph and return the resulting picture.
874 \item[{\tt setcoords($t_x$,\,$t_y$)}]
875 Set up a new coordinate system as specified by numeric flags $t_x$,
876 $t_y$. Flag values are $\pm{\tt linear}$ and $\pm{\tt log}$.
877 \item[{\tt setrange($\descr{coordinates}$,\,$\descr{coordinates}$)}]
878 Set the lower and upper limits for the current coordinate system.
879 Each \tdescr{coordinates} can be a single pair expression or two
880 numeric or string expressions.
881 \end{description}
882
883 \subsection{Drawing and Labeling}
884
885 All of the drawing and labeling commands can be followed by an
886 \tdescr{option list}. In addition to the usual MetaPost drawing options, the
887 list can contain a {\tt plot} \tdescr{picture} clause to plot a specified
888 picture at each data point.
889
890 The drawing and labeling commands are closely related to a set of similarly
891 named commands in plain MetaPost. The {\tt gdrawarrow} and {\tt gdrawdblarrow}
892 commands are included to maintain this relationship.
893
894 \begin{description}
895 \item[{\tt gdotlabel.$\descr{label suffix}$($p$,\,$\descr{location}$)}]
896 This is like {\tt glabel} except it also puts a dot at the location
897 being labeled.
898 \item[{\tt gdraw $p$}]
899 Draw path $p$, or if $p$ is a string, read coordinate pairs from
900 file~$p$ and draw a polygonal line through them.
901 \item[{\tt gdrawarrow $p$}]
902 This is like {\tt dgraw} $p$ except it adds an arrowhead at the end of
903 the path.
904 \item[{\tt gdrawdblarrow $p$}]
905 This is like {\tt dgraw} $p$ except it adds an arrowheads at each end of
906 the path.
907 \item[{\tt gfill $p$}]
908 Fill cyclic path~$p$ or read coordinates from the file named by
909 string~$p$ and fill the resulting polygonal outline.
910 \item[{\tt glabel.$\descr{label suffix}$($p$,\,$\descr{location}$)}]
911 If $p$ is not a picture, it should be a string. Typeset it using
912 {\tt defaultfont}, then place it near the given location and offset as
913 specified by the \tdescr{label suffix}. The \tdescr{location} can be
914 $x$~and $y$ coordinates, a pair giving $x$~and $y$, a numerc value giving
915 a time on the last path drawn, or {\tt OUT} to label the outside of the
916 graph.
917 \end{description}
918
919 \subsection{Grids, Tick Marks, and Framing}
920
921 \begin{description}
922 \item[{\tt auto.}$\descr{{\tt x} or {\tt y}}$]
923 Generate default $x$ or $y$ coordinates for tick marks.
924 \item[{\tt autogrid($\descr{axis label command}$,\,$\descr{axis label command}$)}]
925 Draw default axis labels using the specified commands for the $x$ and
926 $y$ axes. An \tdescr{axis label command} may be \tdescr{empty} or it
927 may be {\tt itick}, {\tt otick}, or {\tt grid} followed by a
928 \tdescr{label suffix}.
929 \item[{\tt frame.}$\descr{label suffix}$\ $\descr{option list}$]
930 Draw a frame around the graph, or draw the part of the frame specified
931 by the \tdescr{label suffix}.
932 \item[{\tt grid.}$\descr{label suffix}$($f$,$z$)]
933 Draw a grid line across the graph from the side specified by the
934 \tdescr{label suffix}, and label it there using format string~$f$ and
935 coordinate value~$z$. If $f$ is a picture, it gives the label.
936 \item[{\tt itick.}$\descr{label suffix}$($f$,$z$)]
937 This is like {\tt grid} except it draws an inward tick mark.
938 \item[{\tt otick.}$\descr{label suffix}$($f$,$z$)]
939 This is like {\tt grid} except it draws an outward tick mark.
940 \end{description}
941
942 \subsection{Miscellaneous Commands}
943
944 \begin{description}
945 \item[{\tt augment.$\descr{variable}$($\descr{coordinates}$)}]
946 Append \tdescr{coordinates} to the path stored in \tdescr{variable}.
947 \item[{\tt format($f$,\,$x$)}]
948 Typeset $x$ according to format string~$f$ and return the resulting
949 picture.
950 \item[{\tt gdata($f$,\,$\descr{variable}$,\,$\descr{commands}$)}]
951 Read the file named by string~$f$ and execute \tdescr{commands} for each
952 input line using the \tdescr{variable} as an array to store data fields.
953 \item[{\tt init\_numbers($s$,\,$m$,\,$x$,\,$t$,\,$e$)}]
954 Provide five pictures as templates for future {\tt format} operations:
955 $s$ is a leading minus; $m$ is a sample mantissa; $x$ follows the
956 mantissa; $t$ is a leading minus for the exponent~$e$.
957 \item[{\tt Mreadpath($f$)}]
958 Read a path for the data file named by string~$f$ and return it in
959 ``{\tt Mlog} form''.
960 \end{description}
961
962 \subsection{Arithmetic on Numeric Strings}
963
964 It is necessary to {\tt input sarith} before using the following macros:
965 \begin{description}
966 \item[{\tt Sabs $x$}]
967 Compute $|x|$ and return a numeric string.
968 \item[{\tt $x$ Sadd $y$}]
969 Compute $x+y$ and return a numeric string.
970 \item[{\tt Scvnum $x$}]
971 Return the numeric value for string $x$.
972 \item[{\tt $x$ Sdiv $y$}]
973 Compute $x/y$ and return a numeric string.
974 \item[{\tt $x$ Sleq $y$}]
975 Return the boolean result of the comparison $x\leq y$.
976 \item[{\tt $x$ Smul $y$}]
977 Compute $x*y$ and return a numeric string.
978 \item[{\tt $x$ Sneq $y$}]
979 Return the boolean result of the comparison $x\neq y$.
980 \item[{\tt $x$ Ssub $y$}]
981 Compute $x-y$ and return a numeric string.
982 \end{description}
983
984 \subsection{Internal Variables and Constants}
985
986 \begin{description}
987 \item[{\tt Autoform}]
988 Format string used by {\tt autogrid}. Default: \verb|"%g"|.
989 \item[{\tt Fe\_base}]
990 What precedes the exponent when typesetting a power of ten.
991 \item[{\tt Fe\_plus}]
992 Picture of the leading plus sign for positive exponents.
993 \item[{\tt Gmarks}]
994 Minimum number of tick marks per axis for {\tt auto} and {\tt autogrid}.
995 Default: 4.
996 \item[{\tt Gminlog}]
997 Minimum largest/smallest ratio for logarithmic spacing with {\tt auto}
998 and {\tt autogrid}. Default: 3.0.
999 \item[{\tt Gpaths}]
1000 Code for coordinates used in {\tt gdraw} and {\tt gfill} paths:
1001 {\tt linear} for standard form, {log} for ``{\tt Mlog} form''.
1002 \item[{\tt Mten}]
1003 The ``{\tt Mlog} form'' for 10.0
1004 \end{description}
1005
1006
1007 \bibliographystyle{plain}
1008 \bibliography{mpgraph}
1009
1010 \end{document}
1011
1012
1013
1014 % Copyright 1990 - 1995 by AT&T Bell Laboratories.
1015
1016 % Permission to use, copy, modify, and distribute this software
1017 % and its documentation for any purpose and without fee is hereby
1018 % granted, provided that the above copyright notice appear in all
1019 % copies and that both that the copyright notice and this
1020 % permission notice and warranty disclaimer appear in supporting
1021 % documentation, and that the names of AT&T Bell Laboratories or
1022 % any of its entities not be used in advertising or publicity
1023 % pertaining to distribution of the software without specific,
1024 % written prior permission.
1025
1026 % AT&T disclaims all warranties with regard to this software,
1027 % including all implied warranties of merchantability and fitness.
1028 % In no event shall AT&T be liable for any special, indirect or
1029 % consequential damages or any damages whatsoever resulting from
1030 % loss of use, data or profits, whether in an action of contract,
1031 % negligence or other tortious action, arising out of or in
1032 % connection with the use or performance of this software.
1033
1034 % In addition, John Hobby, the original author of MetaPost and this
1035 % manual, makes the following requests:
1036 % - I request that it remain clear that I am the author of
1037 % "A User's Manual for MetaPost" and "Drawing Graphs with MetaPost".
1038 % - I request to be consulted before significant changes are made.
1039
1040 %%% Local Variables:
1041 %%% mode: latex
1042 %%% TeX-PDF-mode: t
1043 %%% TeX-master: t
1044 %%% End: