plotutils

168
The GNU Plotting Utilities Programs and functions for vector graphics and data plotting Version 2.4.1 Robert S. Maier and Nicholas B. Tufillaro

Upload: wing-kwong-wong

Post on 02-Oct-2014

70 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: plotutils

The GNU Plotting UtilitiesProgramsandfunctionsfor vectorgraphicsanddataplotting

Version2.4.1

RobertS.MaierandNicholasB. Tufillaro

Page 2: plotutils

Copyright c�

1989–2000FreeSoftwareFoundation,Inc.

Permissionis grantedto makeanddistributeverbatimcopiesof thismanualprovidedthecopyrightnoticeandthispermissionnoticearepreservedon all copies.

Permissionis grantedto copy anddistributemodifiedversionsof this manualundertheconditionsfor verbatimcopying, providedthat theentireresultingderivedwork is distributedunderthetermsof a permissionnoticeidenticalto this one.

Permissionis grantedto copy anddistributetranslationsof thismanualinto anotherlanguage,underthe above conditionsfor modifiedversions,except that this permissionnoticemay be statedin atranslationapprovedby theFoundation.

Page 3: plotutils

i

Table of Contents

1 TheGNU PlottingUtilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

2 Thegraph Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42.1 Simpleexamplesusinggraph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42.2 Non-square,displaced,androtatedplots. . . . . . . . . . . . . . . . . . . . . . . . . 82.3 Preparingaplot from morethanonedataset. . . . . . . . . . . . . . . . . . . . . 92.4 Multiplotting: placingmultiple plotson asinglepage. . . . . . . . . . . 112.5 Readingbinaryandotherdataformats. . . . . . . . . . . . . . . . . . . . . . . . . . 122.6 graph command-lineoptions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

2.6.1 Plot options. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132.6.2 Datasetoptions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202.6.3 Multiplot options. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232.6.4 Raw graph options. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242.6.5 Informationaloptions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

2.7 Environmentvariables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

3 Theplot Program. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273.1 How to useplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273.2 plot command-lineoptions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283.3 Environmentvariables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

4 Thepic2plot Program. . . . . . . . . . . . . . . . . . . . . . . . . . . . 364.1 Whatpic2plot is usedfor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364.2 pic2plot command-lineoptions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374.3 Environmentvariables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

5 The tek2plot Program. . . . . . . . . . . . . . . . . . . . . . . . . . . . 445.1 What tek2plot is usedfor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445.2 tek2plot command-lineoptions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445.3 Environmentvariables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

6 Theplotfont Utility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516.1 How to useplotfont . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516.2 plotfont command-lineoptions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526.3 Environmentvariables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

7 Thespline Program. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597.1 How to usespline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597.2 Advanceduseof spline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 617.3 spline command-lineoptions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

Page 4: plotutils

ii

8 Theode Program. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 668.1 Mathematicalbasics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 668.2 Simpleexamplesusingode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 678.3 Additional examplesusingode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 708.4 ode command-lineoptions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 738.5 Diagnosticmessages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 748.6 Numericalerrorandhow to avoid it . . . . . . . . . . . . . . . . . . . . . . . . . . . . 758.7 Runningtime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 798.8 Theode input languageformally specified. . . . . . . . . . . . . . . . . . . . . 798.9 Bibliographyonode andsolvingdifferentialequations. . . . . . . . . 83

9 libplot , a2-D VectorGraphicsLibrary. . . . . . . . . . . . . 849.1 Programmingwith libplot : An overview . . . . . . . . . . . . . . . . . . . . 849.2 C Programmingwith libplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87

9.2.1 TheC applicationprogramminginterface. . . . . . . . . . . . . 879.2.2 OlderC applicationprogramminginterfaces. . . . . . . . . . 899.2.3 C compilingandlinking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 909.2.4 Sampledrawingsin C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 919.2.5 Simplepathsandcompoundpaths. . . . . . . . . . . . . . . . . . . . 959.2.6 Drawing on aphysicalpage. . . . . . . . . . . . . . . . . . . . . . . . . . 979.2.7 AnimatedGIFsin C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 999.2.8 X Window Systemanimationsin C. . . . . . . . . . . . . . . . . . 1019.2.9 AdvancedX Window Systemprogramming. . . . . . . . . 104

9.3 C++ Programmingwith libplotter . . . . . . . . . . . . . . . . . . . . . . . 1079.3.1 ThePlotter class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1079.3.2 C++ compilingandlinking . . . . . . . . . . . . . . . . . . . . . . . . . 1089.3.3 Sampledrawingsin C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . 109

9.4 Thefunctionsin libplot : A detailedlisting. . . . . . . . . . . . . . . . . 1109.4.1 Controlfunctions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1119.4.2 Object-drawing functions. . . . . . . . . . . . . . . . . . . . . . . . . . . 1139.4.3 Attribute-settingfunctions. . . . . . . . . . . . . . . . . . . . . . . . . . 1189.4.4 Mappingfunctions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125

9.5 Plotterparameters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127

AppendixA Fonts,Strings,andSymbols. . . . . . . . . . . . . . 134A.1 Availabletext fonts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134A.2 Cyrillic andJapanesefonts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139A.3 Availabletext fontsfor theX Window System. . . . . . . . . . . . . . . . 140A.4 Text stringformatandescapesequences. . . . . . . . . . . . . . . . . . . . . . 141A.5 Availablemarker symbols. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153

AppendixB SpecifyingColorsby Name. . . . . . . . . . . . . . . 155

AppendixC PageSizesandViewport Sizes. . . . . . . . . . . . 156

AppendixD TheGraphicsMetafileFormat. . . . . . . . . . . . 158

Page 5: plotutils

iii

AppendixE ObtainingAuxiliary Software. . . . . . . . . . . . . 160E.1 How to get idraw . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160E.2 How to getxfig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160

History andAcknowledgements. . . . . . . . . . . . . . . . . . . . . . . . . 161

ReportingBugs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163

Page 6: plotutils

Chapter1: TheGNU PlottingUtilities 1

1 The GNU Plotting Utilities

The GNU plotting utilities consistof eight command-lineprograms: the graphicsprogramsgraph , plot , pic2plot , tek2plot , and plotfont , and the mathematicalprogramsspline , ode , and double . Distributed with these programs is GNU libplot , thelibrary on which the graphicsprogramsare based. GNU libplot is a function library fordevice-independenttwo-dimensionalvectorgraphics,including vectorgraphicsanimationsundertheX Window System.It hasbindingsfor bothC andC++.

ThegraphicsprogramsandGNU libplot canexportvectorgraphicsin thefollowing formats.

X If thisoutputoptionisselected,thereisnooutputfile. Outputisdirectedtoapopped-upwindow on anX Window Systemdisplay.

PNG This is “portablenetwork graphics”format,which is increasinglypopularon theWeb.UnlikeGIF format,it is unencumberedby patents.Filesin PNGformatmaybeviewedor editedwith many applications,suchasthe free imagedisplayapplicationxv andthefreeImageMagick package.

PNM This is “portableanymap” format. Therearethreetypesof portableanymap: PBM(portable bitmap, for monochromeimages),PGM (portable graymap),and PPM(portablepixmap, for coloredimages). The output file will usewhichever is mostappropriate.Portableanymapsmaybe translatedto otherformatswith thenetpbmpackage.

GIF This is pseudo-GIFformatratherthantrueGIF format. Unlike GIF formatit doesnotuseLZW compression,so it doesnot transgressthe UnisysLZW patent. However,files in pseudo-GIFformatmaybeviewedor editedwith any applicationthatacceptsGIF format,suchasxv andtheImageMagick package.

SVG This is ScalableVector Graphicsformat. SVG is a new, XML-based format forvector graphicson the Web. The W3 Consortium(http://www.w3.o rg ) hasmore information on SVG, which is being developed by its Graphics Activity(http://www.w3.o rg/ Graphi cs ).

AI This is the formatusedby AdobeIllustrator. Files in this formatmaybeeditedwithAdobeIllustrator(version5, andmorerecentversions),or otherapplications.

PS This is idraw -editablePostscriptformat. Files in this format may be sent to aPostscriptprinter, imported into anotherdocument,or editedwith the free idrawdrawing editor. SeeSectionE.1 [idraw], page160.

CGM Thisis ComputerGraphicsMetafileformat,whichmaybeimportedintoanapplicationor displayedin any Web browser with a CGM plug-in. By default, a binary filein version3 CGM format that conformsto the WebCGM profile is produced. TheCGM OpenConsortium(http://www.cgmop en.o rg ) hasmoreinformationonWebCGM,which is astandardfor Web-basedvectorgraphics.

Fig This is a vectorgraphicsformat that may be displayedor editedwith the free xfigdrawing editor. SeeSectionE.2 [xfig], page160.

PCL5 Thisis apowerful versionof Hewlett–Packard’sPrinterControlLanguage.Filesin thisformatmaybesentto a LaserJetprinteror compatibledevice (notethatmostinkjetsdo not supportPCL5).

Page 7: plotutils

Chapter1: TheGNU PlottingUtilities 2

HP-GL This is Hewlett–Packard’s GraphicsLanguage.By default, the modernvariantHP-GL/2 isproduced.Filesin HP-GLorHP-GL/2formatmaybeimportedintoadocumentor sentto aplotter.

ReGIS This is the graphicsformat understoodby several DEC terminals(VT340, VT330,VT241, VT240) and emulators, including the DECwindows terminal emulator,dxterm .

Tek This is the graphicsformat understoodby Tektronix 4014 terminalsandemulators,includingtheemulatorsbuilt into thexterm terminalemulatorprogramandtheMS-DOSversionof kermit .

Metafile This is device-independent GNU graphicsmetafileformat. The plot programcantranslateit to any of theprecedingformats.

Of thecommand-linegraphicsprograms,thebestknown is graph , which is anapplicationforplotting two-dimensionalscientificdata. It readsoneor moredatafiles containingdatasets,andoutputsa plot. Theabove outputformatsaresupported.Thecorrespondingcommandsaregraph-T X, graph -T png , graph -T pnm, graph -T gif , graph -T svg , graph -T ai , graph-T ps , graph -T cgm, graph -T fig , graph -T pcl , graph -T hpgl , graph -T regis ,graph -T tek , andgraph . graph withouta ‘ -T ’ option(referredto as‘raw graph ’) producesoutputin GNU metafileformat.

graph canreaddatasetsin both ASCII andbinary format, anddatasetsin the ‘table’ formatproducedby the plotting programgnuplot . It producesa plot with or without axesandlabels.Youmayspecifylabelsandrangesfor theaxes,andthesizeandpositionof theplot on thedisplay.Thelabelsmaycontainsubscriptsandsubscripts,Greekletters,andotherspecialsymbols;thereisalsosupportfor Cyrillic script (i.e., Russian)andJapanese.You may specifythe type of markersymbolusedfor eachdataset,andsuchparametersasthestyleandthicknessof theline (if any) usedto connectpointsin a dataset.Theplotting of filled regionsis supported,asis thedrawing of errorbars.graph providesfull supportfor multiplotting. With a singleinvocationof graph , you mayproducea multiplot consistingof many plots, eithersideby sideor inset. Eachplot will have itsown axesanddata.

graph -T X, graph -T tek , graph -T regis , andraw graph have a featurethat mostplottingprogramsdonothave. They canacceptinput from apipe,andplot datapointsto theoutputin real time. For this to occur, theusermustspecifyrangesfor bothaxes,sothatgraph doesnotneedto wait until theendof theinputbeforedeterminingthem.

Theplot programis a so-calledplot filter. It cantranslateGNU graphicsmetafiles(producedfor exampleby raw graph ) into any supportedoutputformat. Thecorrespondingcommandsareplot -T X, plot -T png , plot -T pnm, plot -T gif , plot -T svg , plot -T ai , plot-T ps , plot -T cgm, plot -T fig , plot -T pcl , plot -T hpgl , plot -T regis , plot-T tek , andplot . Theplot programis usefulif youwish to produceoutputin severaldifferentformatswhile invoking graph only once. It is also useful if you wish to translatefiles in thetraditional‘plot(5)’ formatproducedby, e.g.,thenon-GNUversionsof graph providedwith someoperatingsystems.GNU metafileformatis compatiblewith plot(5) format.

Thepic2plot programcantranslatefrom thepic languageto any supportedoutputformat.The pic language,which was inventedat Bell Laboratories,is usedfor creatingbox-and-arrowdiagramsof the kind frequently found in technicalpapersand textbooks. The correspondingcommandsarepic2plot -T X, pic2plot -T png , pic2plot -T pnm, pic2plot -T gif ,

Page 8: plotutils

Chapter1: TheGNU PlottingUtilities 3

pic2plot -T ai , pic2plot -T ps , pic2plot -T cgm, pic2plot -T fig , pic2plot-T pcl , pic2plot -T hpgl , pic2plot -T regis , pic2plot -T tek , andpic2plot .

The tek2plot programcantranslatefrom Tektronix format to any supportedoutputformat.The correspondingcommandsare tek2plot -T X, tek2plot -T png , tek2plot -T pnm,tek2plot -T gif , tek2plot -T svg , tek2plot -T ai , tek2plot -T ps , tek2plot -T cgm, tek2plot -T fig , tek2plot -T pcl , tek2plot -T hpgl , tek2plot -T regis ,andtek2plot . tek2plot is usefulif you have anolderapplicationthatproducesdrawings inTektronixformat.

The plotfont programis a simpleutility that displaysa charactermapfor any font that isavailable to graph , plot , pic2plot , or tek2plot . The 35 standardPostscriptfonts areavailableif the‘ -T X’, ‘ -T ai ’, ‘ -T ps ’, ‘ -T cgm’, or ‘ -T fig ’ optionsareused.The45standardPCL5 fonts(i.e.,“LaserJet”fonts)areavailableif the‘ -T ai ’, ‘ -T pcl ’ or ‘ -T hpgl ’ optionsareused.In thelattertwo cases(‘ -T pcl ’ and‘ -T hpgl ’), anumberof Hewlett–Packardvectorfontsareavailableaswell. A setof 22Hershey vectorfonts,includingCyrillic fontsandaJapanesefont,is alwaysavailable. Whenproducingoutputfor anX Window Systemdisplay, any of thegraphicsprogramscanusescalableX fonts.

Of the command-linemathematicalprograms,spline doesspline interpolationof scalarorvector-valued data. It normally useseither cubic spline interpolationor exponentialsplinesintension,but like graph it can function asa real-timefilter undersomecircumstances.Besidessplining datasets,it canconstructcurves,eitheropenor closed,througharbitrarily chosenpointsin � -dimensionalspace.ode providestheability to integratean ordinarydifferentialequationora systemof ordinary differential equations,when provided with an explicit expressionfor eachequation.It supplementstheplottingprogramgnuplot , whichcanplot functionsbut not integrateordinarydifferentialequations.Thefinal command-linemathematicalprogram,double , is afilterfor converting,scalingandcuttingbinaryor ASCII datastreams.It is still underdevelopmentandis not yet documented.

TheGNU libplot functionlibrary, onwhichthecommand-linegraphicsprogramsarebased,is discussedat lengthelsewherein this documentation.It givesC andC++ programstheability todraw suchobjectsaslines,openandclosedpolylines,arcs(bothcircularandelliptic), quadraticandcubicBeziercurves,circlesandellipses,points(i.e.,pixels),marker symbols,andtext strings.Thefilling of objectsotherthanpoints,marker symbols,andtext stringsis supported(fill color, aswellaspencolor, canbesetarbitrarily). Text stringscanbedrawn in any of alargenumberof fonts. The35 standardPostscriptfonts aresupportedby theX Window System,SVG, Illustrator, Postscript,CGM, andxfig drivers,andthe 45 standardPCL5 fonts aresupportedby the SVG, Illustrator,PCL5 andHP-GL/2drivers.Thelattertwo alsosupportanumberof Hewlett–Packardvectorfonts.All drivers,includingthePNG,PNM, GIF, ReGIS,Tektronixandmetafiledrivers,supporta setof22 Hershey vectorfonts.

The supportfor drawing text strings is extensive. Text strings may include subscriptsandsuperscripts,and may include characterschosenfrom more than one font in a typeface. Manynon-alphanumericcharactersmaybeincluded.Theentirecollectionof over1700‘Hershey glyphs’digitized by Allen V. Hershey at the U.S. Naval SurfaceWeaponsCenter, which includesmanycurioussymbols,is built into GNU libplot . Text stringsin theso-calledEUC-JPencoding(theExtendedUnix Codefor Japanese)canbealsobedrawn. Suchstringsmay includebothsyllabicJapanesecharacters(HiraganaandKatakana)andideographicJapanesecharacters(Kanji). GNUlibplot containsa library of 603Kanji, including596of the2965frequentlyusedLevel 1 Kanji.

Page 9: plotutils

Chapter2: Thegraph Application 4

2 The graph Application

Eachinvocationof graph readsoneor moredatasetsfrom filesnamedon thecommandline orfrom standardinput, andpreparesa plot. Therearemany command-lineoptionsfor adjustingthevisualappearanceof theplot. SeeSection2.6 [graphInvocation],page13, for documentationonall options.Thefollowing sectionsexplain how to usethemostfrequentlyusedoptions,by givingexamples.

2.1 Simpleexamplesusinggraph

By default, graph readsASCII datafrom the files specifiedon the commandline, or fromstandardinput if no files arespecified. The dataarepairsof numbers,interpretedasthe � and �coordinatesof datapoints.An examplewould be:

0.0 0.01.0 0.22.0 0.03.0 0.44.0 0.25.0 0.6

Datapointsdo notneedto beondifferentlines,nordo the � and � coordinatesof adatapointneedto beon thesameline. However, thereshouldbeno blanklinesin theinput if it is to beviewedasforming asingledataset.

To plot suchadatasetwith graph , youcoulddo

graph -T ps datafile > plot.ps

or equivalently

graph -T ps < datafile > plot.ps

Eitherof thesewouldproduceanencapsulatedPostscriptfile ‘plot.ps ’, whichcouldbeincludedin anotherdocument,displayedonascreen,sentto aprinter, or editedwith thefreeidraw drawingeditor. The‘ --page-size ’ option,orequivalentlythePAGESIZEenvironmentvariable,specifiesthesizeof thepageonwhichtheplot will bepositioned.Thedefault is " letter" , i.e.,8.5in by 11in,but " a4" or otherISO or ANSI pagesizescouldequallywell bespecified.SeeAppendixC [PageandViewportSizes],page156.

Similarly, youwoulddo

graph -T svg < datafile > plot.svggraph -T cgm < datafile > plot.cgm

to produceSVG and WebCGM files that could be displayedin a Web browser with SVG andWebCGMsupport,or

graph -T fig < datafile > plot.fig

to produceafile ‘plot.fig ’ in Fig formatthatcouldbeeditedwith thefreexfig drawing editor,or

graph -T ai < datafile > plot.ai

to produceafile ‘plot.ai ’ thatcouldbeeditedwith AdobeIllustrator. If youdo

Page 10: plotutils

Chapter2: Thegraph Application 5

graph -T hpgl < datafile > plot.plt

you will producea file ‘plot.plt ’ in the Hewlett–PackardGraphicsLanguage(HP-GL/2) thatmaybesentto a Hewlett–Packardplotter. Similarly, you would usegraph -T pcl to produceafile in PCL 5 formatthatmaybeprintedon aLaserJetor otherlaserprinter.

You would usegraph -T X to popup a window on anX Window Systemdisplay, anddisplaytheplot in it. For that,youwoulddo

graph -T X < datafile

If you usegraph -T X, no outputfile will beproduced:only a window. Thewindow will vanishif you type‘q’ or click your mousein it.

Youmayalsousegraph -T png to produceaPNGfile, graph -T pnmto produceaPNM file(a “portableanymap”),andgraph -T gif to produceapseudo-GIFfile. If thefreeimagedisplayapplicationxv is availableonyour system,youcoulduseany of thethreecommands

graph -T png < datafile | xv -graph -T pnm < datafile | xv -graph -T gif < datafile | xv -

to view theoutputfile.

Anotherthing you cando is usegraph -T tek to displaya plot on a device thatcanemulateaTektronix4014graphicsterminal.xterm , theX Window Systemterminalemulator, cando this.Within anxterm window, youwould type

graph -T tek < datafile

xterm normallyemulatesaVT100terminal,but whenthiscommandis issuedfromwithin it, it willpopup a secondwindow (a ‘Tektronix window’) anddraw the plot in it. The Japaneseterminalemulatorkterm shouldbeableto dothesame,providedthatit is correctlyinstalled.Anotherpieceof softwarethatcanemulateaTektronix4014terminalis theMS-DOSversionof kermit .

In thesameway, you would usegraph -T regis to displaya plot on any graphicsterminalor emulatorthat supportsReGISgraphics.dxterm , theDECwindows terminalemulator, candothis. SeveralDEC terminals(in particulartheVT340, VT330, VT241, andVT240 terminals)alsosupportReGISgraphics.

graph maybehave differentlydependingon theenvironmentin which it is invoked. We havealreadymentionedthe PAGESIZE environmentvariable,which affects the operationof graph-T svg , graph -T ai , graph -T ps , graph -T cgm, graph -T fig , graph -T pcl , andgraph -T hpgl . Similarly, the BITMAPSIZE environment variable affects the operationofgraph -T X, graph -T png , graph -T pnm, andgraph -T gif . TheDISPLAY environmentvariableaffectstheoperationof graph -T X, andtheTERMenvironmentvariableaffectstheoper-ationof graph -T tek . Therearealsoseveralenvironmentvariablesthataffect theoperationofgraph -T pcl andgraph -T hpgl . For acompletediscussionof theeffectsof theenvironmentongraph , seeSection2.7[graphEnvironment],page25. Thefollowing remarksapplyirrespectiveof whichoutputformatis specified.

By default, successive points in the datasetare joined by solid line segments,which form apolygonal line or polyline that we call simply a ‘line’. You may choosethe style of line (the‘linemode’)with the‘ -m’ option:

graph -T ps -m 2 < datafile > plot.ps

Here‘ -m 2’ indicatesthat linemode#2 shouldbeused.If thedatasetis renderedin monochrome,which is the default, the line canbe drawn in oneof five distinct styles. Linemodes#1 through

Page 11: plotutils

Chapter2: Thegraph Application 6

#5 signify solid, dotted,dotdashed,shortdashed,andlongdashed;thereafterthesequencerepeats.If the ‘ -C ’ option is used,thedatasetwill be renderedin color. For coloreddatasets,the line canbedrawn in oneof 25 distinctstyles. Linemodes#1 through#5 signify red,green,blue,magenta,andcyan; all aresolid. Linemodes#6 through#10signify thesamefive colors,but dottedratherthansolid. Linemodes#11 through#16signify thesamefive colors,but dotdashed,andso forth.After linemode#25,thesequencerepeats.Linemode#0, irrespective of whethertherenderingis inmonochromeor color, meansthattheline is notdrawn.

You maywish to fill thepolygonboundedby theline (i.e., shadeit, or fill it with a solid color).For this,you wouldusethe‘ -q ’ option. For example,

echo .1 .1 .1 .9 .9 .9 .9 .1 .1 .1 |graph -T ps -C -m 1 -q 0.3 > plot.ps

will plot a squareregion with vertices(0.1,0.1),(0.1,0.9),(0.9,0.9),and(0.9,0.1).Therepetitionofthefirst vertex (0.1,0.1)at theendof thesequenceof verticesensuresthatthesquarewill beclosed:all four segmentsof its boundarywill bedrawn. Thesquarewill bedrawn in red,sincethecoloredversionof linemode#1 is requested.Theinteriorof thesquarewill befilled with redto anintensityof 30%, asthe‘ -q 0.3 ’ optionspecifies.If theintensitywere1.0, theregion would befilled withsolid color, andif it were0.0, theregion would befilled with white. If theintensitywerenegative,theregionwould beunfilled,or transparent(thedefault).

Youmayspecifythethickness(‘width’) of theline, whetherit is filled or not,by usingthe‘ -W’option. For example, ‘ -W 0.01 ’ specifiesthattheline shouldhave a thicknessequalto 0.01timesthe sizeof the graphicsdisplay. Also, you may put symbolsat eachdatapoint alongthe line bydoing,for example,

graph -T ps -S 3 0.1 < datafile > plot.ps

wherethe first argument3 indicateswhich symbol to plot. The optional secondargument0.1specifiesthesymbolsizeasa fractionof thesizeof the‘plotting box’: thesquarewithin which theplot is drawn. Symbol#1 is adot,symbol#2 is aplussign,symbol#3 is anasterisk,symbol#4 is acircle,symbol#5 is across,andsoforth. (SeeSectionA.5 [Marker Symbols],page153.) Symbols1 through31 arethesamefor all displaytypes,andthecolor of a symbolwill be thesameasthecolor of theline it is plottedalong.

Actually, you would probablynot want to plot symbolsat eachpoint in thedatasetunlessyouturn off the line joining the points. For this purpose,the ‘negative linemode’ conceptis useful.A line whoselinemodeis negative is not visible; however, any symbolsplottedalongit will havethecolorassociatedwith thecorrespondingpositive linemode.So,for example,

graph -T ps -C -m -3 -S 4 < datafile > plot.ps

will plot abluecircleateachdatapoint. Thecircleswill notbejoinedby line segments.By addingtheoptionalsecondargumentto the‘ -S ’ option,youmayadjustthesizeof thecircles.

graph will automaticallygenerateabscissa(i.e., � ) valuesfor you if you usethe ‘ -a ’ option.If this option is used,no abscissavaluesshouldbe given in the datafile. The datapointswill betakento beregularlyspacedalongtheabscissa.Thetwo argumentsfollowing ‘ -a ’ onthecommandline will be takenasthesamplinginterval andtheabscissavalueof thefirst datapoint. If they areabsent,they default to 1.0and0.0respectively. For example,thecommand

echo 0 1 0 | graph -T ps -a > plot.ps

producesexactly thesameplot as

echo 0 0 1 1 2 0 | graph -T ps > plot.ps

Page 12: plotutils

Chapter2: Thegraph Application 7

If the ‘ -I e’ option is specified,graph will plot datawith errorbars. In this casethedatasetshouldconsistof triples( � ,� ,error), ratherthanpairs( ���� ). A verticalerrorbarof theappropriatelengthwill be plottedat eachdatapoint. You would plot a symbolat eachdatapoint, alongwiththeerrorbar, by usingthe‘ -S ’ optionin theusualway. Thesymbolwill bethesamefor eachpointin thedataset.You mayusethe‘ -a ’ optionin conjunctionwith ‘ -I e’, if you wish. If you do, thedatasetshouldcontainnoabscissa(i.e., � ) values.

By default, the limits on the � and � axes,andthe spacingbetweenthe labeledticks on eachaxis,arecomputedautomatically. Youmaywish to setthemmanually. You wouldaccomplishthiswith the‘ -x ’ and‘ -y ’ options.

echo 0 0 1 1 2 0 | graph -T ps -x -1 3 -y -1 2 > plot.ps

will producea plot in which the � axis extendsfrom 1 to 3, and the � axis from 1 to 2. Bydefault,graph triesto placeaboutsix numberedticksoneachaxis. By includinganoptionalthirdargumentto ‘ -x ’ or ‘ -y ’, you may manuallyset the spacingof the labeledticks. For example,using‘ -y -1 2 1’ ratherthan‘ -y -1 2’ will producea � axiswith labeledticksat 1, 0, 1, and2,ratherthanat thelocationsthatgraph wouldchooseby default,whichwouldbe 1, 0.5,0, 0.5,1, 1.5,and2. In general, if a third argumentis presentthenlabeledtickswill beplacedateachof itsintegermultiples.

To make anaxislogarithmic,youwouldusethe‘ -l ’ option. For example,

echo 1 1 2 3 3 1 | graph -T ps -l x > plot.ps

will producea plot in which the � axis is logarithmic,but the � axis is linear. To make bothaxeslogarithmic,you would use‘ -l x -l y ’. By default, theupperandlower limits on a logarithmicaxisarepowersof ten,andtherearetick marksateachpowerof tenandat its integermultiples.Thetick marksat thepowersof tenarelabeled.If theaxisspansmorethanfiveordersof magnitude,thetick marksat theintegermultiplesareomitted.

If youhaveanunusuallyshortlogarithmicaxis,youmayneedto increasethenumberof labeledticks. To do this,youshouldspecifya tick spacingmanually. For example, ‘ -l x -x 1 9 2’ wouldproducea plot in which the � axis is logarithmicandextendsfrom 1 to 9. Labeledticks would belocatedat eachintegermultiple of 2, i.e.,at 2, 4, 6, and8.

Youwould labelthe � and � axeswith the‘ -X ’ and‘ -Y ’ options,respectively. For example,

echo 1 1 2 3 3 1 | graph -T ps -l x -X "A Logarithmic Axis" > plot.ps

will label thelog axisin theprecedingexample.By default, thelabelfor the � axis(if any) will berotated90degrees,unlessyouusethe‘ --toggle-rotate- y-l abel ’ option. Youmayspecifya ‘top label’, or title for theplot, by usingthe‘ -L ’ option. Doing, for example,

echo 1 1 2 3 3 1 | graph -T ps -l x -L "A Simple Example" > plot.ps

will produceaplot with a title on top.

Thefont sizeof the � axisand � axislabelsmaybespecifiedwith the‘ -f ’ option,andthefontsizeof thetitle with the‘ --title-font-si ze ’ option. For example,

echo 1 1 2 3 3 1 | graph -T ps -X "Abscissa" -f 0.1 > plot.ps

will producea plot in which thefont sizeof the � axis label,andeachof thenumericaltick labels,is very large(0.1 timesthesizeof theplottingbox, i.e., thesquarewithin which theplot is drawn).

The font in which the labelsspecifiedwith the ‘ -X ’, ‘ -Y ’, and‘ -L ’ optionsaredrawn canbespecifiedwith the ‘ -F ’ option. For example,‘ -F Times-Roman ’ will make the labelsappearinTimes-Romaninsteadof thedefaultfont (whichisHelvetica,unless‘ -T png ’, ‘ -T pnm’, ‘ -T gif ’,

Page 13: plotutils

Chapter2: Thegraph Application 8

‘ -T pcl ’, ‘ -T hpgl ’, ‘ -T regis ’, or ‘ -T tek ’ is specified). Font namesarecase-insensitive,so ‘ -F times-roman ’ will work equallywell. The available fonts include35 Postscriptfonts(for all variantsof graph otherthangraph -T png , graph -T pnm, graph -T gif , graph-T pcl , graph -T hpgl , graph -T regis , andgraph -T tek ), 45PCL 5 fonts(for graph-T svg , graph -T ai , graph -T pcl and graph -T hpgl ), a numberof Hewlett–Packardvectorfonts(for graph -T pcl andgraph -T hpgl ), and22Hershey vectorfonts. TheHersheyfonts includeHersheyCyrillic, for Russian,andHersheyEUC, for Japanese.For a discussionoftheavailablefonts,seeSectionA.1 [Text Fonts],page134. Theplotfont utility will produceacharactermapof any availablefont. SeeChapter6 [plotfont], page51.

The format of the labelsdrawn with the ‘ -X ’, ‘ -Y ’, and ‘ -L ’ optionsmay be quite intricate.Subscripts,superscripts,squareroots,andswitchingfonts within a typefaceareall allowed. Theaboveexamplesdonotillustratethis,but for details,seeSectionA.4 [Text StringFormat],page141.

Eachof the precedingexamplesproducesa plot containingthe default sort of grid (a squareplotting box,with ticks andlabelsdrawn alongits lower edgeandits left edge).Thereareactuallyseveral sorts of grid you may request. The ‘ -g 0’, ‘ -g 1’, ‘ -g 2’, and ‘ -g 3’ options yieldsuccessively fanciergrids. What they yield, respectively, is nogrid atall, apair of axeswith ticksandlabels,a squareplotting box with ticks andlabels,anda squareplotting box with ticks, labels,andgrid lines. As youcancheck,‘ -g 2’ is thedefault. Thereis alsoa ‘ -g 4’ option,whichyieldsaslightly differentsortof grid: apairof axesthatcrossat theorigin. This lastsortof grid is usefulwhenthe � or � coordinatesof thedatapointsyou areplotting arebothpositive andnegative.

2.2 Non-square,displaced,androtatedplots

To alterthelineardimensionsof theplottingbox,andalsoto positionit in adifferentpartof thegraphicsdisplay, youcoulddosomethinglike

graph -T ps -h .3 -w .6 -r .1 -u .1 < datafile > plot.ps

Herethe ‘ -h ’ and‘ -w ’ optionsspecifytheheightandwidth of theplotting box, andthe‘ -r ’ and‘ -u ’ optionsindicatehow far up andto theright thelower left cornerof theplotting box shouldbepositioned.All dimensionsareexpressedasfractionsof thesizeof thegraphicsdisplay. By default,theheightandwidth of theplotting box equal0.6,andthe ‘upwardshift’ andthe‘rightwardshift’equal0.2. Sotheabove examplewill producea plot that is half astall asusual. Comparedto itsusualposition,theplot will beshiftedslightly downwardandto theleft.

Severalcommand-lineoptionsspecifysizesor dimensionsasfractionsof thesizeof theplottingbox. For example,‘ -S 3 .01 ’ specifiesthat themarker symbolsfor the following datasetshouldbe of type#3, andshouldhave a font sizeequalto 0.01, i.e., 0.01 timesthe minimum dimension(heightor width) of theplottingbox. If the‘ -h ’ or ‘ -w ’ optionsareemployedto expandor contracttheplot, suchsizesor dimensionswill scalein tandem.Thatis presumablytheright thing to do.

To rotateyour plot by 90 degreescounterclockwise,you would add‘ --rotation 90 ’ to thegraph commandline. You may alsospecify ‘ --rotation 180 ’, to producean upside-downplot, or ‘ --rotation 270 ’. The‘ --rotation ’ optionmaybecombinedwith the‘ -h ’, ‘ -w ’,‘ -r ’, and‘ -u ’ options.If they appeartogether, the‘ --rotation ’ optiontakeseffectfirst. Thatisbecause‘ --rotation ’ specifiestherotationangleof thegraphicsdisplay, while theotheroptionsspecifyhow the plotting box shouldbe positionedwithin the graphicsdisplay. The two sortsofpositioningarelogically distinct.

Thegraphicsdisplay(sometimescalledthe ‘viewport’) is an abstraction.For graph -T X, itis a popped-upwindow on an X display. For graph -T pnm andgraph -T gif , it is a square

Page 14: plotutils

Chapter2: Thegraph Application 9

or rectangularbitmap. In thesethreecases,thesizeof thegraphicsdisplaycanbesetby usingthe‘ --bitmap-size ’ option, or by settingthe BITMAPSIZE environmentvariable. For graph-T tek , thegraphicsdisplayis a squareregion occupying thecentralpartof a Tektronixdisplay.(Tektronixdisplaysare4/3 timesaswide asthey arehigh.) For graph -T regis , it is a squareregion occupying thecentralpartof a ReGISdisplay. For graph -T ai , graph -T ps , graph-T pcl , andgraph -T fig , by default it is a 8-inchsquarecenteredon an 8.5in by 11in page(US lettersize).For graph -T hpgl , it is an8-inchsquare,whichby default is not centered.Forgraph -T svg andgraph -T cgm, thedefault graphicsdisplayis an8-inchsquare,thoughif theoutputfile is placedon aWebpage,it maybescaledarbitrarily.

Thepagesize,which determinesthedefault displaysizeusedby graph -T svg , graph -Tai , graph -T ps , graph -T cgm, graph -T fig , graph -T pcl , andgraph -T hpgl , canbe setby usingthe ‘ --page-size ’ option,or by settingtheenvironmentvariablePAGESIZE.For example, settingthe pagesizeto " a4" would produceoutput for an A4-sizepage(21cm by29.7cm),andwould selecta appropriategraphicsdisplaysize. Eitheror bothof thedimensionsofthe graphicsdisplaycanbe specifiedexplicitly. For example,the pagesizecould be specifiedas" letter,xsize=4in" , or " a4,xsize=10cm,ysize=15cm" . Thedimensionsof thegraphicsdisplayareallowedto benegative (anegative dimensionresultsin a reflection).

The position of the display on the page,relative to its default position, may optionally beadjustedby specifyingan offset vector. For example, the pagesize could be specifiedas " let-ter,yoffset=1.2in" , or " a4,xoffset= 5mm,yoffset=2.0cm" . It is alsopossibleto positionthegraph-icsdisplayprecisely, byspecifyingthelocationof its lowerleft cornerrelativeto thelowerleft cornerof thepage.For example,thepagesizecouldbespecifiedas" letter,xorigin=2in,yorigin=3in" , or" a4,xorigin=0.5cm,yorigin=0.5cm" .

The precedingoptionsmay be intermingled. However, graph -T svg andgraph -T cgmignorethe" xoffset" , " yoffset" , " xorigin" , and" yorigin" options,sinceSVGformatandWebCGMformathave nonotionof theWebpageonwhich thegraphicsdisplaywill ultimatelybepositioned.They interpretthe" xsize" and" ysize" optionsasspecifyingadefault sizefor thegraphicsdisplay(it is merelya default, sincethe outputfile may be scaledarbitrarily whenit is placedon a Webpage).

For moreinformationon pageandgraphicsdisplaysizes,seeAppendixC [PageandViewportSizes],page156.

2.3 Preparinga plot from morethanonedataset

It is frequentlythecasethat severaldatasetsneedto bedisplayedon thesameplot. If so, youmaywish to distinguishthepointsin differentdatasetsby joining themby linesof differenttypes,or by usingmarker symbolsof differenttypes.

A morecomplicatedexamplewould bethefollowing. You mayhave a file containinga datasetthat is theresultof experimentalobservations,andafile containingcloselyspacedpointsthattraceout a theoreticalcurve. Thesecondfile is a datasetin its own right. You would presumablyplotit with line segmentsjoining successive datapoints,so asto traceout the theoreticalcurve. Butthefirst dataset,resultingfrom experiment,would beplottedwithout suchline segments.In fact, amarker symbolwouldbeplottedateachof its points.

Theseexamples,andotherslike them,led us to definea setof seven attributesthat definetheway a datasetshouldbeplotted. Theseattributes,which canbesetby command-lineoptions,arethefollowing.

Page 15: plotutils

Chapter2: Thegraph Application 10

1. color/monochrome

2. linemode

3. linewidth

4. symboltype

5. symbolsize

6. symbolfont name

7. fill fraction

Color/monochrome(a choiceof oneor the other) is the simplest. The choiceis toggledwith the‘ -C ’ option. The ‘linemode’ (i.e., line style) specifieshow the line segmentsjoining successivepointsshouldbedrawn; it is specifiedwith the‘ -m’ option. Linemode#0meansno linemodeatall,for example. ‘Linewidth’ meansline thickness;it is specifiedwith the‘ -W’ option. ‘Symbol type’and ‘symbol size’, which arespecifiedwith the ‘ -S ’ option, specify the symbol plottedat eachpoint of the dataset.‘Symbol font name’refersto the font from which marker symbols#32 andabove, which aretaken to becharactersratherthangeometricsymbols,areselected.It is setwiththe‘ --symbol-font-n ame’ option,andis relevantonly if ‘ -S ’ is usedto requestsuchspecialmarker symbols.Finally, thepolygonalline joining thepointsin a datasetmaybefilled, to createa filled or shadedpolygon. The ‘fill fraction’ is setwith the ‘ -q ’ option. A negative fill fractionmeansno fill, or transparent;zeromeanswhite,and1.0meanssolid,or fully colored.

Theprecedingsevenattributesreferto theway in whichdatasetsareplotted.Datasetsmayalsodiffer from oneanotherin theway in which they arereadfrom files. Thedataset(s)in a file mayor maynot containerrorbars,for example. If afile containsdatawith errorbars,the‘ -I e’ optionshouldoccuronthecommandline beforethefile name.(The‘ -I ’ optionspecifiestheinput formatfor thefollowing files.)

Thefollowingillustrateshow datasetsin threedifferentinputfilescould beplottedsimultaneously.graph -T ps -m 0 -S 3 file1 -C -m 3 file2 -C -W 0.02 file3 > output.ps

Thedatasetin file1 will beplottedin linemode#0,sosuccessivepointswill notbejoinedby lines.But symbol#3 (anasterisk)will beplottedat eachpoint. Thedatasetin file2 will beplottedincolor, andlinemode#3will beused.In colorplotting,linemode#3is interpretedasasolidblueline.Thesecond‘ -C ’ onthecommandline turnsoff colorfor file3 . Thepointsin thethird datasetwillbejoinedby a blackline with thickness0.02,asa fractionof thesize(i.e.,minimumdimension)ofthegraphicsdisplay.

Theabovecommandline couldbemadeevenmorecomplicatedby specifyingadditionaloptions(e.g., ‘ -q ’ or ‘ -I ’) beforeeachfile. In fact the commandline could also includesuchstandardoptionsas‘ -x ’ or ‘ -y ’, whichspecifytherangeof eachaxis. Suchoptions,which referto theplotasa wholeratherthanto individual datasets,shouldappearbeforethefirst file name.For example,youcoulddo

graph -T ps -x 0 1 0.5 -m 0 -S 3 file1 -C -m 3 file2 > output.ps

Note that it is possibleto includethe specialfile name‘ - ’, which refersto standardinput, on thecommandline. Soyoumaypipetheoutputof anotherprograminto graph . Youmayevengenerateaplot in partfrom pipedoutput,andin partfrom files.

Eachinput file may includemorethanonedataset.If so, thecommandline optionsprecedinga file on thecommandline will take effect for all datasetsin thatfile. Therearetwo exceptionstothis. By default, thelinemodeis incremented(‘bumped’)from onedatasetto thenext. This featureis usuallyquiteconvenient.For example, if youdo

Page 16: plotutils

Chapter2: Thegraph Application 11

graph -T ps -m 3 file1 > output.ps

thefirst datasetin file1 will appearin linemode#3,thesecondin linemode#4,etc. In fact, if youdo

graph -T ps file1 file2 . . . > output.ps

without specifyinglinemodeexplicitly, thesuccessive datasetsreadfrom thefiles on thecommandline will appearin linemode#1, linemode#2, . . . . If you do not like this feature,you mayturn itoff, or in generaltoggleit, by usingthe‘ -B ’ option.

You mayalsocontrolmanuallythe linemodeandsymboltypeusedfor thedatasetswithin anyfile. You would do this by includingdirectivesin thefile itself, ratherthanon thecommandline.For example,if theline

#m=-5,S=10

appearedin anASCII-formatinput file, it would beinterpretedasa directive to switchto linemode# � 5 andsymbol type #10 for the following dataset.Futurereleasesof graph may provide theability to seteachof thesevendatasetattributesin thisway.

2.4 Multiplotting: placingmultiple plots on a singlepage

It is occasionallyusefulto displayseveralplotsatonceon asinglepage,or onasinglegraphicsdisplay. We call sucha compositeplot a multiplot. Onecommonsortof multiplot is a small plotinsetinto a largerone.Anothersortis two or moreplotssideby side.

graph candraw multiplotsconsistingof anarbitrarily largenumberof plots. Whenmultiplot-ting,graph drawseachplot in its own ‘virtual display’. Whenanordinaryplot is drawn, thevirtualdisplay is the sameasthe physicaldisplay. But whena plot of a multiplot is drawn, the virtualdisplaymaybeany smallersquareregion. Thefollowing two-plotexampleillustratestheidea.

graph -T X datafile1 --reposition .35 .35 .3 datafile2

Heredatafile1 is plottedin theusualway. The ‘ --reposition ’ option,which servesasaseparatorbetweenplots, specifiesthat the secondplot will be drawn in a virtual display. For thepurposesof the ‘ --reposition ’ option, thephysicaldisplayis a squarewith lower left corner(0.0,0.0)andupperright corner(1.0,1.0). In thosecoordinatesthevirtual displaywill bea squareof size0.3,with lower left corner(0.35,0.35).Sothesecondplot will beinsetinto thefirst.

Justas the ‘ -w ’, ‘ -h ’, ‘ -r ’, and ‘ -u ’ optionsmay be usedto set the sizeandpositionof aplottingboxwithin thephysicaldisplay, sothey maybeusedto setthesizeandpositionof aplottingboxwithin avirtual display. For example,

graph -T X datafile1 --reposition .35 .35 .3 -w .4 -r .3 datafile2

will yield a two-plot multiplot in which thesecondplot is significantlydifferent. Its plotting boxwill have a width only 0.4 timesthewidth of thevirtual display. However, theplotting box will becenteredwithin thevirtual display, sincethedistancebetweentheleft edgeof theplotting box andtheleft edgeof thevirtual displaywill be0.3timesthewidth of thevirtual display.

By convention,beforeeachplot of a multiplot otherthanthefirst is drawn, a ‘blankout region’surroundingits plotting box is erased.(Thatis, it is filled with white, or whatever thebackgroundcolor is.) Thiserasurepreventstheplotsfrom overlappingandproducingamessyresult.By default,theblankout region is a rectangularregion 30%larger in eachdimensionthantheplotting box forthe plot. That is appropriateif the plot is a small onethat is inset into the first plot. It may notbe appropriate,however, if you are preparinga multiplot in which several plots appearside by

Page 17: plotutils

Chapter2: Thegraph Application 12

side. You may usethe ‘ --blankout ’ option to adjustthis parameter. For example, specifying‘ --blankout 1.0 ’ will make the blankout region for a plot coincide with its plotting box.Specifying ‘ --blankout 0.0 ’ will prevent any blanking out from occurring. The blankoutparametermaybesetmorethanonce,soasto differ from plot to plot.

It shouldbe emphasizedthat every plot in a multiplot is a plot in its own right. All the usualoptions(‘ -m’, ‘ -S ’, ‘ -x ’, ‘ -y ’, etc.) canbeappliedto eachplot separately. Theoptionsfor a plotshouldoccuron the graph commandline immediatelyafter the ‘ --reposition ’ option thatappliesto it. Eachplot maybepreparedfrom morethana singledataset,also. Thenamesof thedatafiles for eachplot shouldoccuron thecommandline beforethefollowing ‘ --reposition ’option,if any.

2.5 Readingbinary andotherdataformats

By default,graph readsdatasetsin ASCII format. But it canalsoreaddatasetsin any of threebinaryformats(singleprecisionfloatingpoint,doubleprecisionfloatingpoint,andinteger). Thesethreeinput formatsarespecifiedby the‘ -I d’, ‘ -I f ’, and‘ -I i ’ options,respectively.

Therearetwo advantagesto usingbinarydata: 1) graph runssignificantlyfasterbecausethecomputationaloverheadfor converting datafrom ASCII to binary is eliminated,and2) the inputfiles maybesignificantlysmaller. If you have very largedatasets,usingbinaryformatmayreducestorageandruntimecosts.

For example,you may createa single precisionbinary datasetas output from a C languageprogram:

#include <stdio.h>void write_point (float x, float y){

fwrite(&x, sizeof (float), 1, stdout);fwrite(&y, sizeof (float), 1, stdout);

}

Youmayplot datawritten thisway by doing:

graph -T ps -I f < binary_datafile > plot.ps

Theinclusionof multiple datasetswithin a singlebinaryfile is supported.If a binaryfile containsmorethana singledataset,successive datasetsshouldbe separatedby a singleoccurrenceof thethelargestpossiblenumber. For singleprecisiondatasetsthis is thequantityFLT_MAX, for doubleprecisiondatasetsit is thequantityDBL_MAX, andfor integerdatasetsit is thequantityINT_MAX.On mostmachinesFLT_MAXis approximately3 � 4 � 10��� , DBL_MAXis approximately1 � 8 � 10����� ,andINT_MAX is 2���� 1.

If youarereadingdatasetsfrom morethanonefile, it is not requiredthatthefilesbein thesameformat. For example,

graph -T ps -I f binary_datafile -I a ascii_datafile > plot.ps

will readbinary_datafile in ‘ f ’ (binary single precision)format, and datafile in ‘a’(normalASCII) format.

Thereis currentlyno supportfor readingandplotting binarydatawith errorbars. If you havedatawith errorbars,youshouldsupplythedatato graph in ASCII, andusethe‘ -I e’ option.

Page 18: plotutils

Chapter2: Thegraph Application 13

graph canalsoreaddatafiles in theASCII ‘table’ formatproducedby thegnuplot plottingprogram.For this,youshouldusethe‘ -I g’ option. Suchadatafile mayconsistof morethanonedataset.

Tosumup: therearesixsupporteddataformats,‘a’ (normalASCII), ‘e’ (ASCII with errorbars),‘g’ (the ASCII ‘table’ format producedby gnuplot ), ‘ f ’ (binary singleprecision),‘d’ (binarydoubleprecision),and‘ i ’ (binaryinteger). Input filesmaybein any of thesesix formats.

2.6 graph command-lineoptions

Thegraph programreadsoneor moredatasetsfrom filesnamedon thecommandline or fromstandardinput, andpreparesa plot. The output format or displaytype is specifiedwith the ‘ -T ’option.

By default,graph readsASCII datafrom thefilesspecifiedon thecommandline. Thedataarepairsof numbers,interpretedasthe � and � coordinatesof datapoints. If no files arespecified,orthefile name‘ - ’ is specified,thestandardinput is read.An outputfile is written to standardoutput,unlessthe‘ -T X’ optionis specified.In thatcasethegraphis displayedin apopped-upwindow onanX Window Systemdisplay, andthereis no outputfile.

Thereare many command-lineoptionsfor adjustingthe visual appearanceof the plot. Therelative orderof file namesandcommand-lineoptionsis important.Only theoptionsthatprecedeafile nameon thecommandline take effect for thatfile.

Thefollowing sectionslist thepossibleoptions.Eachoptionthattakesanargumentis followed,in parentheses,by thetypeanddefault valueof theargument.Therearefivesortsof option.

1. Optionsaffectinganentireplot. (SeeSection2.6.1[Plot Options],page13.)

2. Optionsaffectingthereadinganddrawingof individual datasetswithin aplot. (SeeSection2.6.2[DatasetOptions],page20.)

3. Optionsfor multiplotting (drawing several plots at once). (SeeSection2.6.3[Multiplot Op-tions],page23.)

4. Optionsrelevantonly to raw graph , i.e., relevantonly if no displaytypeor outputformat isspecifiedwith the‘ -T ’ option. (SeeSection2.6.4[Raw graphOptions],page24.)

5. Optionsrequestinginformation(e.g.,‘ --help ’). (SeeSection2.6.5[Info Options],page24.)

2.6.1 Plot options

Thefollowing optionsaffectanentireplot. They shouldnormallyoccuratmostonce,andshouldappearonthecommandline beforethefirst file name.If amultiplot is beingdrawn, they may(withthe exceptionof the ‘ -T ’ option) occurmore thanonce. If so, the secondand later occurrencesshouldbeplacedonthecommandline immediatelyaftereach‘ --reposition x y’ option,whichseparatestheplotsin amultiplot.

‘ -T type’‘ --display-type type’

(String,default " meta" .) Selecta displaytype or outputformat of type type, whichmaybe oneof thestrings" X" , " png" , " pnm" , " gif" , " svg" , " ai" , " ps" , " cgm" ," fig" , " pcl" , " hpgl" , " regis" , " tek" , and" meta" . Theserefer respectively to theX Window System, PNGformat,portableanymap(PBM/PGM/PPM)format,pseudo-GIF format,thenew XML-basedScalableVectorGraphicsformat,theformatusedby

Page 19: plotutils

Chapter2: Thegraph Application 14

AdobeIllustrator, idraw -editablePostscript,theWebCGMformatfor Web-basedvec-tor graphics,theformatusedby thexfig drawing editor, theHewlett–PackardPCL 5printerlanguage,theHewlett–PackardGraphicsLanguage(by default, HP-GL/2),theReGIS(remotegraphicsinstructionset)formatdevelopedby DEC, Tektronixformat,anddevice-independentGNU graphicsmetafileformat.

‘ -E x| y’‘ --toggle-axis-e nd x| y’

Setthepositionof the indicatedaxis to be on theotherendof theplotting box fromwhat is currentlythecase.E.g., ‘ -E y ’ will causethe � axisto appearon theright oftheplot ratherthantheleft, whichis thedefault. Similarly, ‘ -E x ’ will causethe � axisto appearat thetop of theplot ratherthanthebottom. Note that if the � axisappearsat thetop,noplot title will bedrawn, sincetherewill benoroom.

‘ -f size’‘ --font-size size’

(Float,default 0.0525.)Setthesizeof thefont usedfor theaxisandtick labelsto besize. Thesizeis specifiedasafractionof theminimumdimension(width or height)oftheplottingbox.

‘ -F font name’‘ --font-name font name’

(String,default " Helvetica" exceptfor graph -T pcl , for which " Univers" is thedefault, and graph -T png , graph -T pnm, graph -T gif , graph -T hpgl ,graph -T regis ,graph -T tek , andraw graph , for all of which" HersheySerif"is the default.) Set the font usedfor the axis and tick labels,and for the plot title(if any), to befont name. Thechoiceof font for theplot title maybeoverriddenwiththe ‘ --title-font-nam e’ option (seebelow). Font namesarecase-insensitive.If the specifiedfont is not available, the default font will be used. Which fonts areavailabledependsonwhich ‘ -T ’ optionis used.For a list of all fonts,seeSectionA.1[Text Fonts],page134. Theplotfont utility will producea charactermapof anyavailablefont. SeeChapter6 [plotfont], page51.

‘ -g grid style’‘ --grid-style grid style’

(Integer in therange0. . .4, default 2.) Setthegrid style for theplot to begrid style.Gridstyles0 through3areprogressively morefancy, butstyle4 isasomewhatdifferentstyle.

0. no axes,tick marksor labels.

1. apairof axes,with tick marksandlabels.

2. boxaroundplot, with tick marksandlabels.

3. boxaroundplot, with tick marksandlabels;alsogrid lines.

4. axesintersectat theorigin, with tick marksandlabels.

‘ -h height’‘ --height-of-plo t height’

(Float,default0.6.) Setthefractionalheightof theplot with respectto theheightof thedisplay(or virtual display, in thecaseof a multiplot) to beheight. A valueof 1.0willproducea plotting box thatfills theentireavailablearea.Sincelabelsandtick marks

Page 20: plotutils

Chapter2: Thegraph Application 15

maybeplacedoutsidetheplottingbox,valuesconsiderablylessthan1.0arenormallychosen.

‘ -H ’‘ --toggle-frame- on- to p’

Togglewhetheror not a copy of the plot frameshouldbe drawn on top of the plot,aswell asbeneathit. This optionis usefulwhentheplotteddataset(s)projectslightlybeyondtheframe,whichcanhappenif alargeline thicknessorsymbolsizeisspecified.

‘ -k length’‘ --tick-size length’

(Float,default .02.) Setthelengthof thetick marksoneachaxisto belength. A valueof 1.0producestick markswhoselengthis equalto theminimumdimension(width orheight)of theplottingbox. A negative lengthyieldstick marksthatextendoutsidethebox, ratherthaninside.

‘ -K clip mode’‘ --clip-mode clip mode’

(Integer, default 1.) Set the clip modefor the plot to clip mode. The clip modeisrelevantonly if datapointsarebeingjoinedby a line, andtheline is notbeingfilled tocreateafilled region (sincefilled regionsareclippedin afixedway).

Thereare threeclip modes: 0, 1, and2. They have the samemeaningas in thegnuplot plotting program.Clip mode0 meansthata line segmentjoining two datapointswill be plottedonly if neitherpoint is outsidethe plotting box. Clip mode1meansthat it will beplottedif no morethanoneof thetwo pointsis outside,andclipmode2 meansthat it will beplottedeven if bothareoutside. In all threeclip modestheline segmentwill beclippedto theplottingbox.

‘ -l x| y’‘ --toggle-log-ax is x| y’

Setthespecifiedaxisto bealog axisratherthanalinearaxis,or viceversa.By default,bothaxesarelinearaxes.

‘ -L top label’‘ --top-label top label’

(String,defaultempty.) Placethetext stringtop label above theplot, asits ‘top label’,i.e., title. The string may include escapesequences(seeSectionA.4 [Text StringFormat], page141). The ‘ --title-font-siz e’ option may be usedto specifythe size of the font. The font is normally the sameas the font usedfor labelingaxesandticks, asselectedby the ‘ -F ’ option. But this canbe overriddenwith the‘ --title-font-na me’ option.

‘ -N x| y’‘ --toggle-no-tic ks x| y’

Togglethepresenceof ticks andtick labelson thespecifiedaxis. This appliesto thegrid stylesthatnormallyincludeticks andtick labels,i.e.,grid styles1, 2, 3, and4.

‘ -r right’‘ --right-shift right’

(Float,default0.2.) Movetheplot to theright by afractionalamountright with respectto thewidth of thedisplay(or virtual display, in thecaseof amultiplot). Thisproduces

Page 21: plotutils

Chapter2: Thegraph Application 16

amargin on theleft sideof theplottingbox. A valueof 0.5will produceamargin halfthewidth of the availablearea. Note that the tick marksandlabelsaredrawn in themargin.

‘ -R x| y’‘ --toggle-round- to- next -t ic k x| y’

Toggle whetheror not the upperand lower limits of the specifiedaxis should beexpanded,so that they bothbecomeintegermultiplesof thespacingbetweenlabeledtick marks.

This option is meaningfulwhenever theuserspecifieseitheror bothof the limits, byusing the ‘ -x ’ or ‘ -y ’ option. If the userleaves both limits unspecified,they willalwaysbechosento satisfythe‘integermultiple’ constraint.

‘ -s ’‘ --save-screen ’

Save thescreen.Thisoptionrequeststhatgraph noterasetheoutputdevicebeforeitbeginsto plot.

This option is relevant only to graph -T tek andraw graph . Tektronix displaysandemulatorsarepersistent,in thesensethatpreviouslydrawngraphicsremainvisible.Soby repeatedlyusinggraph -T tek -s , youcanbuild up amultiplot.

‘ -t ’‘ --toggle-transp ose -a xe s ’

Transposetheabscissaandordinate.This causestheaxesto beinterchanged,andtheoptionsthatapplytoeachaxistobeappliedto theoppositeaxis. Thatis,datapointsarereadin as( � �! ) pairs,andsuchoptionsas‘ -x ’ and‘ -X ’ applyto the � axisratherthanthe ! axis. If the ‘ -I e’ option is in force,so that thedatapointsarereadwith errorbars,theorientationof theerrorbarswill beswitchedbetweenverticalandhorizontal.

‘ -u up’‘ --upward-shift up’

(Float, default 0.2.) Move the plot up by a fractionalamountup with respectto theheightof thedisplay(or virtual display, in the caseof a multiplot). This producesamargin below theplottingbox. A valueof 0.5will produceamargin half theheightoftheavailablearea.Notethatthetick marksandlabelsaredrawn in themargin.

‘ -w width’‘ --width-of-plot width’

(Float,default 0.6.) Setthefractionalwidth of theplot with respectto thewidth of thedisplay(or virtual display, in thecaseof a multiplot) to bewidth. A valueof 1.0willproducea plotting box thatfills theentireavailablearea.Sincelabelsandtick marksmaybeplacedoutsidetheplottingbox,valuesconsiderablylessthan1.0arenormallychosen.

‘ -x [ lower limit [ upperlimit [ spacing]]] ’‘ --x-limits [ lower limit [ upperlimit [ spacing]]] ’

(Floats.) Theargumentslower limit andupperlimit specifythe limits of the ! axis,andtheoptionalargumentspacingspecifiesthespacingof labeledticksalongtheaxis.If any of thethreeargumentsis missingor is suppliedas‘ - ’ (i.e.,asasinglehyphen),

Page 22: plotutils

Chapter2: Thegraph Application 17

it is computedfrom the data. Both argumentslower limit andupperlimit mustbepresentif graph is to actasa real-timefilter.

By default,thesuppliedlimit(s) arestrictly respected.However, the‘ -R x ’ optionmaybeusedto requestthat they beroundedto thenearestintegermultiple of thespacingbetweenlabeledticks. Thelower limit will beroundeddownward,andtheupperlimitupward.

‘ -X x label’‘ --x-label x label’

(String,default empty.) Setthe label for the " axis to be the text stringx label. Thestringmayincludeescapesequences(seeSectionA.4 [Text StringFormat],page141).The‘ -F ’ and‘ -f ’ optionsmaybeusedto specifythenameof thefont andthesizeofthefont.

‘ -y [ lower limit [ upperlimit [ spacing]]] ’‘ --y-limits [ lower limit [ upperlimit [ spacing]]] ’

(Floats.)Theargumentsspecifythelimits of the # axis,andthespacingof labeledticksalong it, asfor the " axis (seeabove). Both argumentslower limit andupperlimitmustbepresentif graph is to actasa real-timefilter.

By default, the suppliedlimit(s) arestrictly respected.However, the ‘ -R y ’ optionmaybeusedto requestthatthey beroundedto thenearestmultipleof thetick spacing.Thelower limit will beroundeddownward,andtheupperlimit upward.

‘ -Y y label’‘ --y-label y label’

(String,default empty.) Setthe label for the # axis to be the text string y label. Thestringmayincludeescapesequences(seeSectionA.4 [Text StringFormat],page141).The label will be rotatedby 90 degreesso that it is parallel to the axis, unlessthe‘ --toggle-rotate -y- la bel ’ optionis used.Someold X Window Systemdis-playsdonotsupportrotatedlabels,andrequirethe‘ --toggle-rotate -y -la bel ’option. The‘ -F ’ and‘ -f ’ optionscanbeusedto specifythenameof thefont andthesizeof thefont.

‘ --bg-color name’(String, default " white" .) Set the color usedfor the plot backgroundto be name.This is relevant only to graph -T X, graph -T png , graph -T pnm, graph -Tgif , graph -T cgm, graph -T regis , andgraph -T meta . An unrecognizednamesetsthe color to the default. For informationon what namesare recognized,seeAppendixB [Color Names],page155. TheenvironmentvariableBG_COLORcanequallywell beusedto specifythebackgroundcolor.

If the ‘ -T png ’ or ‘ -T gif ’ option is used,a transparentPNG file or a transparentpseudo-GIF, respectively, may be producedby settingthe TRANSPARENT_COLORenvironmentvariableto the nameof the backgroundcolor. SeeSection2.7 [graphEnvironment],page25. If the ‘ -T svg ’ or ‘ -T cgm’ option is used,an outputfilewithout abackgroundmaybeproducedby settingthebackgroundcolor to " none" .

‘ --bitmap-size bitmapsize’(String,default " 570x570" .) Setthesizeof thegraphicsdisplayin whichtheplot willbedrawn, in termsof pixels,to bebitmap size. This is relevantonly to graph -T X,

Page 23: plotutils

Chapter2: Thegraph Application 18

graph -T png , graph -T pnm, andgraph -T gif , for all of which thesizecanbeexpressedin termsof pixels. TheenvironmentvariableBITMAPSIZE mayequallywell beusedto specifythesize.

Thegraphicsdisplayusedby graph -T X is apopped-upX window. Command-linepositioningof thiswindow onanX Window Systemdisplayissupported.Forexample,if bitmapsizeis " 570x570+0+0" thenthewindow will bepoppedupin theupperleftcorner.

If youchoosearectangular(non-square)window size,thefontsin theplotwill bescaledanisotropically, i.e., by different factorsin the horizontalandvertical direction. Forthis,graph -T X requiresanX11R6display. Any font thatcannotbeanisotropicallyscaledwill be replacedby a default scalablefont, suchas the Hershey vector font" HersheySerif" .

Forbackwardcompatibility, graph -T Xallowstheusertosetthewindow sizeandpo-sition by settingtheX resourceXplot.geometry , insteadof ‘ --bitmap-size ’or BITMAPSIZE .

‘ --emulate-color option’(String, default " no" .) If option is " yes" , replaceeachcolor in the output by anappropriateshadeof gray. This is seldomuseful,exceptwhenusing‘graph -T pcl ’to prepareoutput for a PCL5 device. (Many monochromePCL 5 devices, suchasmonochromeLaserJets,do a poor job of emulatingcolor on their own. They usuallymapHP-GL/2’ssevenstandardpencolors,includingevenyellow, to black.) Youmayequallywell requestcolor emulationby settingtheenvironmentvariableEMULATE_COLORto " yes" .

‘ --frame-color name’(String, default " black" .) Set the color usedfor drawing the plot frame, and fordrawing monochromedatasets(if any) to be name. An unrecognizednamesetsthecolor to thedefault. For informationon whatnamesarerecognized,seeAppendixB[Color Names],page155.

‘ --frame-line-wi dth frame line width’(Float,default $ 1.0.) Setthethicknessof linesin theplot frame,asafractionof thesize(i.e., minimum dimension)of the graphicsdisplay, to frame line width. A negativevaluemeansthatthedefaultvaluefor thelinethicknessprovidedbytheGNU libplotgraphicslibrary shouldbe used. This is usually1/850timesthe sizeof the display,althoughif ‘ -T X’, ‘ -T png ’, ‘ -T pnm’, or ‘ -T gif ’ is specified,it is zero. Byconvention,azero-thicknessline is thethinnestline thatcanbedrawn. This is thecasein all outputformats.Note,however, thatthedrawing editorsidraw andxfig treatzero-thicknesslinesasinvisible.

graph -T tek andgraph -T regis donotsupportdrawing lineswith otherthanadefault thickness,andgraph -T hpgl doesnot supportdoingsoif theenvironmentvariableHPGL_VERSIONis setto avaluelessthan" 2" (thedefault).

‘ --max-line-leng th max line length’(Integer, default 500.) Setthemaximumnumberof pointsthatapolygonalline drawnthroughany datasetmay contain,beforeit is flushedto the outputdevice, to equalmax line length. If this flushingoccurs,the polygonalline will be split into two or

Page 24: plotutils

Chapter2: Thegraph Application 19

moresub-lines,thoughthesplitting shouldnot benoticeable.Splitting will not takeplaceif the‘ -q ’ option,which requestsfilling, is used.

The reasonfor splitting long polygonallines is that somedisplaydevices (e.g.,oldPostscriptprintersandHP-GLpenplotters)havelimitedbuffer sizes.TheenvironmentvariableMAX_LINE_LENGTHcanalsobeusedto specifythemaximumline length.Thisoptionhasnoeffectongraph -T tek or raw graph , sincethey draw polylinesin realtime andhave no buffer limitations.

‘ --page-size pagesize’(String,default " letter" .) Setthesizeof thepageonwhichtheplot will bepositioned.This is relevant only to graph -T svg , graph -T ai , graph -T ps , graph -Tcgm, graph -T fig , graph -T pcl , and graph -T hpgl . " letter" meansan8.5in by 11in page.Any ISOpagesizein therange" a0" . . . " a4" or ANSI pagesizein therange" a" . . . " e" maybespecified(" letter" is analiasfor " a" and" tabloid"is analiasfor " b" ). " legal" , " ledger" , and" b5" arerecognizedpagesizesalso.TheenvironmentvariablePAGESIZEcanequallywell beusedto specifythepagesize.

For graph -T ai , graph -T ps , graph -T pcl , andgraph -T fig , thegraph-ics display(or ‘viewport’) within which theplot is drawn will be,by default, a squareregioncenteredonthespecifiedpage.For graph -T hpgl , it will beasquareregionof thesamesize,but maybepositioneddifferently. Eitheror bothof thedimensionsof the graphicsdisplaycanbe specifiedexplicitly. For example,pagesizecould bespecifiedas" letter,xsize=4in" , or " a4,xsize=10cm,ysize=15cm" . Thedimensionsareallowedto benegative (anegative dimensionresultsin a reflection).

The positionof the graphicsdisplay, relative to its default position,may optionallybeadjustedby specifyinganoffset vector. For example,pagesizecouldbespecifiedas " letter,yoffset=1.2in" , or " a4,xoffset=% 5mm,yoffset=2.0cm" . It is alsopossibleto positionthe graphicsdisplayprecisely, by specifyingthe locationof its lower leftcornerrelative to the lower left cornerof the page. For example,pagesizecould bespecifiedas" letter,xorigin=2in,yorigin=3in" , or " a4,xorigin=0.5cm,yorigin=0.5cm" .The precedingoptionsmay be intermingled. graph -T svg and graph -T cgmignorethe" xoffset" , " yoffset" , " xorigin" , and" yorigin" options,sinceSVG formatandWebCGMformathave no notionof theWebpageon which thegraphicsdisplaywill ultimately be positioned. For more on pagesizes,seeAppendix C [PageandViewportSizes],page156.

‘ --pen-colors colors’(String, default " 1=red:2=green:3=blue:4=magenta:5=cyan" .) Set the colorsof thepensusedfor drawing plots, asnumbered,to be colors. The format shouldbe self-explanatory. An unrecognizednamesetsthecorrespondingcolor to thedefault. Forinformationonwhatnamesarerecognized,seeAppendixB [Color Names],page155.

‘ --rotation angle’(Integer, default 0.) Settherotationangleof thegraphicsdisplayto beangledegrees.Recognizedvaluesare0, 90, 180, and270. The rotation is counterclockwise.Theenvironment variableROTATIONcan equally well be usedto specify the rotationangle.

This option is usedfor switchingbetweenportrait andlandscapeorientations.Post-modernistsmayalsofind it useful.

Page 25: plotutils

Chapter2: Thegraph Application 20

‘ --title-font-na mefont name’(String,default " Helvetica" exceptfor graph -T pcl , for which " Univers" is thedefault, and graph -T png , graph -T pnm, graph -T gif , graph -T hpgl ,graph -T regis , andgraph -T tek , for all of which " HersheySerif" is thede-fault.) Setthefont usedfor theplot title to befont name. Normally thefont usedfortheplot title is thesameasthatusedfor labelingtheaxesandtheticks alongtheaxes,asspecifiedby the‘ -F ’ option. But the‘ --title-font-na me’ optioncanbeusedto overridethis. Fontnamesarecase-insensitive. If thespecifiedfont is notavailable,thedefault font will beused.Which fontsareavailabledependsonwhich ‘ -T ’ optionis used.For a list of all fonts,seeSectionA.1 [Text Fonts],page134. Theplotfontutility will producea charactermapof any available font. SeeChapter6 [plotfont],page51.

‘ --title-font-si ze size’(Float,default0.07.)Setthesizeof thefont usedfor thetop label(‘title’), asspecifiedby the ‘ -L ’ option, to be size. The size is specifiedas a fraction of the minimumdimension(width or height)of theplottingbox.

‘ --toggle-rotate -y- la bel ’Positionthelabelon the & axis(which is setwith the‘ -Y ’ option)horizontallyinsteadof vertically, or vice versa.By default, the label is rotated,so that it is parallelto the& axis. But someoutputdevices(e.g.,old X Window Systemdisplays)cannothandlerotatedfonts.

2.6.2 Datasetoptions

Thefollowing optionsaffect theway in which individualdatasetsarereadfrom files,anddrawnaspartof a plot. They shouldappearon thecommandline beforethefile containingthedatasetswhosereadingor renderingthey will affect. They mayappearmorethanonceon a commandline,if morethanonefile is to beread.

Thefollowing threeoptionsaffect theway in whichdatasetsarereadfrom files.

‘ -I data-format’‘ --input-format data-format’

Thisspecifieswhich formatthesubsequentinputfile(s) arein.

‘a’ ASCII format. Eachinput file is a sequenceof floating point numbers,interpretedasthe ' and & coordinatesof thesuccessive datapointsin adataset.The ' and & coordinatesof a point neednot appearon thesameline, andpointsneednot appearon different lines. But if a blank lineoccurs(i.e., two newlines in successionareseen),it is interpretedastheendof a dataset,andthebeginningof thenext.

‘e’ ASCII format, including error bars. Similar to ‘a’ format, except thattriples( ' ,& ,error) appearinsteadof pairs( ')(& ).

‘g’ TheASCII ‘table’ formatproducedby thegnuplot plotting program.

‘ f ’ Single precisionbinary format. Each input file is a sequenceof sin-gle precisionfloatingpoint numbers,interpretedasforming pairs( ' ,& ).Successive datasetsareseparatedby a singleoccurrenceof thequantity

Page 26: plotutils

Chapter2: Thegraph Application 21

FLT_MAX, which is the largestpossiblesingleprecisionfloating pointnumber. On mostmachinesthis is approximately3 * 4 + 10,�- .

‘d’ Doubleprecisionbinary format. Eachinput file is a sequenceof dou-ble precisionfloatingpoint numbers,interpretedasforming pairs( . ,/ ).Successive datasetsareseparatedby a singleoccurrenceof thequantityDBL_MAX, which is the largestpossibledoubleprecisionfloating pointnumber. On mostmachinesthis is approximately1 * 8 + 10,�0�- .

‘ i ’ Integerbinaryformat.Eachinputfile isasequenceof integers,interpretedas forming pairs ( . ,/ ). Successive datasetsare separatedby a singleoccurrenceof thequantity INT_MAX, whichisthelargestpossible integer.On mostmachinesthis is 2,1�2 1.

‘ -a [ stepsize[ lower limit ]] ’‘ --auto-abscissa [ stepsize[ lower limit ]] ’

(Floats,defaults1.0and0.0.) Automaticallygenerateabscissa( . ) values.Irrespectiveof dataformat (‘a’, ‘e’, ‘ f ’, ‘d’, or ‘ i ’), this option specifiesthat the abscissa( . )valuesaremissingfrom the input file: thedataset(s)to bereadcontainonly ordinate( / ) values.Theincrementfrom each. valueto thenext will bestepsize, andthefirst. valuewill be lower limit . To returnto readingabscissavaluesfrom the input, i.e.,for subsequentinputfiles,youwoulduse‘ -a 0’, whichdisablesautomaticgenerationof theabscissavaluesandreturnsstepsizeandlower limit to theirdefault values.

‘ -B ’‘ --toggle-auto-b ump’

By default, thelinemode(setwith ‘ -m’, seebelow) is ‘bumped’(incrementedby unity)at thebeginningof eachnew dataset.This optiontogglesauto-bumping: it turnsit offif it wason,andon if it wasoff.

The following optionsaffect the way in which individual datasetsaredrawn aspart of a plot.Theseoptionssetthesix ‘attributes’(symboltype,symbolfont, linemode,linethickness,fill fraction,andcolor/monochrome)thateachdatasethas.

‘ -m line mode’‘ --line-mode line mode’

(Integer, default 1.) line mode specifiesthe mode (i.e., style) of the lines drawnbetweensuccessive points in a dataset.By convention, linemode#0 meansno lineatall (datapointsaredisconnected).If thedatasetis beingrenderedin monochrome,theinterpretationof line modeis asfollows.

1. solid

2. dotted

3. dotdashed

4. shortdashed

5. longdashed

Thereafter(i.e., for line modegreaterthan5) thesequenceof five linemodesrepeats.Sobesideslinemode#0,thereareatotalof fivedistinctmonochromelinemodes.If thedatasetis being renderedin color (as may be requestedwith the ‘ -C ’ option), theinterpretationof linemodes#1 through#5 is instead

Page 27: plotutils

Chapter2: Thegraph Application 22

1. red,solid

2. green,solid

3. blue,solid

4. magenta,solid

5. cyan,solid

Linemodes#6 through#10 usethe samefive colors,but aredotted; linemodes#11through#15aredotdashed;linemodes#16through#20areshortdashed;andlinemodes#21through#25arelongdashed.Sobesideslinemode#0,thereareatotalof 25distinctcoloredlinemodes.A negative linemodeindicatesthat no line shouldbe drawn, butthatthemarkersymbol,if any (seebelow), shouldbein thecolorof thecorrespondingpositive linemode.

‘ -S [ symbolnumber[ symbolsize]] ’‘ --symbol [ symbolnumber[ symbolsize]] ’

(Integer andfloat, defaults 0 and0.03.) Draw a marker symbolat eachdatapoint.symbolnumberspecifiesthesymboltype,andsymbolsizespecifiesthe font sizeofthesymbol,asa fractionof theminimumdimension(width or height)of theplottingbox. If thedatasetis beingrenderedin color, thesymbolwill have thecolorof thelinethatis beingdrawn to connectthedatapoints.

If youusethe‘ -S ’ option,youwouldusuallyalsousethe‘ -m’ option,to requestthatthe symbolsbe drawn without any line connectingthem. By specifyinga negativeargumentto ‘ -m’ (a ‘negative linemode’),youmayobtaincoloredsymbols.

The following table lists the first few symbols(by convention, symbol#0 meansno symbolatall).

1. dot ( 3 )2. plus(+)

3. asterisk( 4 )4. circle ( 5 )5. cross( 6 )

Marker symbols0. . .31 arefurnishedby the GNU libplot graphicslibrary. SeeSectionA.5 [Marker Symbols],page153. Symbol numbersgreaterthan or equalto 32 are interpretedas charactersin a symbol font, which can be set with the‘ --symbol-font-n ame’ option(seebelow).

‘ -W line width’‘ --line-width line width’

(Float,default 7 1.0.) Setthe thicknessof the lines usedto join successive pointsina dataset,asa fractionof thesize(i.e., minimumdimension)of thegraphicsdisplay,to line width. A negative value meansthat the default value for the line thicknessprovidedby theGNU libplot graphicslibrary shouldbeused.Thisis usually1/850timesthesizeof thedisplay, althoughif ‘ -T X’, ‘ -T png ’, ‘ -T pnm’, or ‘ -T gif ’ isspecified,it is zero.By convention,azero-thicknessline is thethinnestline thatcanbedrawn. This is thecasein all outputformats.Note,however, that thedrawing editorsidraw andxfig treatzero-thicknesslinesasinvisible.

Page 28: plotutils

Chapter2: Thegraph Application 23

graph -T tek andgraph -T regis donotsupportdrawing lineswith otherthanadefault thickness,andgraph -T hpgl doesnot supportdoingsoif theenvironmentvariableHPGL_VERSIONis setto avaluelessthan" 2" (thedefault).

‘ -q fill fraction’‘ --fill-fraction fill fraction’

(Float,default 8 1.0.) If successive pointsin a datasetarejoinedby line segments,settheshadingintensityfor thepolygonformedby the line segmentsto be fill fraction.A solidpolygon(i.e.,onefilled with the‘pencolor’ usedfor drawing thelinesegments)is obtainedby choosingfill fraction=1.0. Theinterior of thepolygonwill bewhite iffill fraction=0.0. Thepolygonwill beunfilled (transparent)if fill fraction is negative.

If thepolygonintersectsitself, the‘even-oddfill rule’ will normallybeusedto deter-minewhich pointsareinsideratherthanoutside,i.e., to determinewhich portionsofthe polygonshouldbe shaded.The even-oddfill rule is explainedin the PostscriptLanguageReferenceManual.

The ‘ -q ’ option hasno effect on graph -T tek , and it is only partly effective ingraph -T hpgl if theenvironmentvariableHPGL_VERSIONis setto a valuelessthan" 2" (thedefault).

‘ -C ’‘ --toggle-use-co lor ’

Toggle betweencolor and monochromerenderingof datasets. The interpretationof linemode dependson whether the rendering is being performed in color ormonochrome;seethe‘ -m’ optionabove.

‘ --symbol-font-n amesymbol font name’(String, default " ZapfDingbats" unless‘ -T png ’, ‘ -T pnm’, ‘ -T gif ’, ‘ -T pcl ’,‘ -T hpgl ’, ‘ -T regis ’, or -T tek is specified,in whichcaseit is " HersheySerif" .)Setthesymbolfont, from whichmarkersymbolsnumbered32andhigherareselected,to be symbol font name. Font namesare case-insensitive. If the specifiedfont isnot available, the default font will be used. Which fonts are available dependsonwhich ‘ -T ’ option is used. For example, if the ‘ -T pcl ’ or ‘ -T hpgl ’ option isusedthen normally the Wingdingsfont, which is an alternative sourceof symbols,becomesavailable.For a list of all fonts,seeSectionA.1 [Text Fonts],page134. Theplotfont utility will producea charactermapof any availablefont. SeeChapter6[plotfont], page51.

2.6.3 Multiplot options

Thefollowing optionsareusedfor multiplotting (placingmorethana singleplotson a display,or a page).The‘ --reposition ’ directive servesasa separator, on thecommandline, betweentheoptionsandfile namesthatapplyto successive plots.

‘ --reposition x y size’(Floats,defaults0.0,0.0,1.0)Setthe‘virtual display’within whichthenext plotwill bedrawn to beasquareof sizesize, with lower left corner(x,y). Normalizedcoordinatesareusedhere:(0,0)meansthelower left cornerof thephysicaldisplayand(1,1)meanstheupperright cornerof thephysicaldisplay. Thesizeof theplot within thevirtualdisplaymay be adjustedwith the ‘ -h ’ and‘ -w ’ options,andits positionwithin the

Page 29: plotutils

Chapter2: Thegraph Application 24

virtual displaywith the ‘ -u ’ and‘ -w ’ options. After a ‘ --reposition ’ directive,theargumentsof thosefour optionswill be interpretedin termsof thevirtual display,not thephysicaldisplay.

‘ --blankout blankout fraction’(Float, default 1.3.) Beforeeachadditionalplot of a multiplot is drawn, the regionof thedisplaythat theplot will occupy is cleared. If blankout fraction=1.3, a region30%larger in eachdimensionis cleared. If, for example,blankout fraction=1.0, theregion coveredby theplot’s plotting box, andno more, is cleared.Thedefault value,1.3,is appropriatefor insetplots. 1.0wouldbeappropriatefor sideby sideplots.

graph -T tek cannotclearregions,andgraph -T hpgl cannotclearthemif theenvironmentvariablesHPGL_VERSIONandHPGL_OPAQUE_MODEaresetto non-default values(i.e.,valuesotherthan" 2" and" yes" , respectively).

2.6.4 Raw graph options

Thefollowing option is relevantonly to raw graph , i.e., is relevantonly if no displaytypeoroutput format is specifiedwith the ‘ -T ’ option. In this casegraph outputsa graphicsmetafile,which may be translatedto other formatsby invoking plot . This option shouldappearon thecommandline beforeany file names,sinceit affectstheoutputof theplot (or multiplot) asawhole.

‘ -O ’‘ --portable-outp ut ’

Outputtheportable(human-readable)versionof GNU metafileformat, ratherthanabinary version(the default). This canalsobe requestedby settingthe environmentvariableMETA_PORTABLEto " yes" .

2.6.5 Informationaloptions

Thefollowing optionsrequestinformation.

‘ --help ’ Print a list of command-lineoptions,andthenexit.

‘ --help-fonts ’Print a tableof availablefonts,andthenexit. Thetablewill dependon which displaytype or output format is specifiedwith the ‘ -T ’ option. graph -T X, graph -T svg , graph -T ai , graph -T ps , graph -T cgm, and graph -T fig eachsupportthe 35 standardPostscriptfonts. graph -T svg , graph -T ai , graph-T pcl , andgraph -T hpgl supportthe45 standardPCL 5 fonts,andgraph -Tpcl andgraph -T hpgl supporta numberof Hewlett–Packardvector fonts. Allof the preceding,togetherwith graph -T png , graph -T pnm, graph -T gif ,graph -T regis , and graph -T tek , supporta set of 22 Hershey vector fonts.Raw graph in principlesupportsany of thesefonts,sinceits outputmustbetranslatedto otherformatswith plot . Theplotfont utility will producea charactermapofany availablefont. SeeChapter6 [plotfont], page51.

‘ --list-fonts ’Like ‘ --help-fonts ’, but lists the fonts in a singlecolumnto facilitatepiping tootherprograms.If no displaytypeor outputformat is specifiedwith the‘ -T ’ option,thefull setof supportedfontsis listed.

Page 30: plotutils

Chapter2: Thegraph Application 25

‘ --version ’Print theversionnumberof graph andtheplottingutilities package,andexit.

2.7 Environmentvariables

The behavior of graph is affected by several environment variables. We have alreadymentioned the environment variables BITMAPSIZE , PAGESIZE, BG_COLOR, EMULATE_COLOR, MAX_LINE_LENGTH, and ROTATION. They serve as backups for the severaloptions ‘ --bitmap-size ’, ‘ --page-size ’, ‘ --bg-color ’, ‘ --emulate-colo r ’,‘ --max-line-leng th ’, and ‘ --rotation ’. The remaining environment variables arespecificto individual outputformats.

graph -T X, which popsup a window on an X Window Systemdisplayanddraws graphicsin it, checkstheDISPLAY environmentvariable.Thevalueof this variabledeterminesthedisplayon which thewindow will bepoppedup.

graph -T png and graph -T gif , which produceoutput in PNG andpseudo-GIFformatrespectively, areaffectedby two environmentvariables. If thevalueof the INTERLACEvariableis " yes" , the output file will be interlaced. Also, if the value of the TRANSPARENT_COLORenvironmentvariableis thenameof acolor thatappearsin theoutputfile, thatcolor will betreatedas transparentby most applications. For information on what color namesare recognized,seeAppendixB [Color Names],page155.

graph -T pnm, which producesoutputin PortableAnymap(PBM/PGM/PPM)format, is af-fectedby thePNM_PORTABLEenvironmentvariable. If its valueis " yes" , theoutputfile will bein the portable(humanreadable)versionof PBM, PGM, or PPM format, ratherthan the default(binary)version.

graph -T cgm, which producesCGM files that comply with the WebCGMprofile for Web-basedvectorgraphics,is affectedby two environmentvariables.By default,aversion3 CGM file isgenerated.Many olderCGM interpretersandviewers,suchastheonesbuilt into Microsoft Officeand other commercialsoftware, only supportversion1 CGM files. The CGM_MAX_VERSIONenvironmentvariablemay be setto " 1" , " 2" , " 3" , or " 4" (the default) to specifyan maximumvaluefor theversionnumber. TheCGM_ENCODINGvariablemayalsobeset,to specifythe typeof encodingusedin the CGM file. Supportedvaluesare" clear text" (i.e., humanreadable)and" binary" (thedefault). TheWebCGMprofile requiresthatthebinaryencodingbeused.

graph -T pcl , which producesPCL 5 outputfor Hewlett–Packardprinters,is affectedby theenvironmentvariablePCL_ASSIGN_COLORS. It shouldbesetto " yes" whenproducingPCL 5output for a color printer or othercolor device. This will ensureaccuratecolor reproductionbygiving theoutputdevice completefreedomin assigningcolors,internally, to its “logical pens”. Ifit is " no" then the device will usea fixed setof coloredpens,andwill emulateothercolorsbyshading.Thedefault is " no" becausemonochromePCL 5 devices,which aremorecommonthancoloredones,mustuseshadingto emulatecolor.

graph -T hpgl , whichproducesHewlett–PackardGraphicsLanguageoutput,is alsoaffectedby several environmentvariables. The most importantis HPGL_VERSION, which may be setto" 1" , " 1.5" , or " 2" (thedefault). " 1" meansthattheoutputshouldbegenericHP-GL," 1.5" meansthattheoutputshouldbesuitablefor theHP7550AgraphicsplotterandtheHP758x,HP7595AandHP7596Adraftingplotters(HP-GLwith someHP-GL/2extensions),and" 2" meansthattheoutputshouldbe modernHP-GL/2. If the versionis " 1" or " 1.5" thenthe only available fonts will be

Page 31: plotutils

Chapter2: Thegraph Application 26

vectorfonts,andall lines will be drawn with a default thickness(the ‘ -W’ option will not work).Additionally, if the versionis " 1" thenthe filling of arbitrarycurveswith solid color will not besupported(the ‘ -q ’ option may be usedto fill circlesandrectanglesalignedwith the coordinateaxes,though).

The positionof the graph -T hpgl graphicsdisplayon the pagecanbe rotated90 degreescounterclockwiseby settingthe HPGL_ROTATEenvironmentvariableto " yes" . This is not thesameasthe rotationobtainedwith the ‘ --rotation ’ option, sinceit both rotatesthe graphicsdisplayandrepositionsits lower left cornertowardanothercornerof thepage.Besides" no" and" yes" , recognizedvaluesfor the HPGL_ROTATEvariableare " 0" , " 90" , " 180" , and" 270" ." no" and" yes" areequivalent to " 0" and" 90" , respectively. " 180" and" 270" aresupportedonly if HPGL_VERSIONis " 2" (thedefault).

Opaquefilling andthe drawing of visible white lines aresupportedonly if HPGL_VERSIONis " 2" (the default) andthe environmentvariableHPGL_OPAQUE_MODEis " yes" (the default).If thevalueis " no" thenopaquefilling will notbeused,andwhitelines(if any), whicharenormallydrawn with pen#0, will not be drawn. This featureis to accommodateolder HP-GL/2 devices.HP-GL/2penplotters,for example, donotsupportopacityor theuseof pen#0to draw visiblewhitelines. SomeolderHP-GL/2devicesreportedlymalfunctionif askedto draw opaqueobjects.

By default, graph -T hpgl will draw with a fixedsetof pens. Which pensarepresentmaybe specifiedby settingthe HPGL_PENSenvironmentvariable. If HPGL_VERSIONis " 1" , thedefault valueof HPGL_PENSis " 1=black" ; if HPGL_VERSIONis " 1.5" or " 2" , thedefault valueof HPGL_PENSis " 1=black:2=red:3=green:4=yellow:5=blue:6=magenta:7=cyan" . The formatshouldbe self-explanatory. By settingHPGL_PENS, you may specifya color for any penin therange#1. . .#31. For informationon what color namesare recognized,seeAppendix B [ColorNames],page155. Pen#1 mustalwaysbepresent,thoughit neednot beblack. Any otherpenintherange#1. . .#31maybeomitted.

If HPGL_VERSIONis " 2" then graph -T hpgl will also be affectedby the environmentvariableHPGL_ASSIGN_COLORS. If thevalueof this variableis " yes" , thengraph -T hpglwill not berestrictedto thepalettespecifiedin HPGL_PENS: it will assigncolorsto “logical pens”in the range#1. . .#31, asneeded. The default value is " no" becauseother thancolor LaserJetprintersandDesignJetplotters,notmany HP-GL/2devicesallow theassignmentof colorsto logicalpens.In particular, HP-GL/2penplottersdo not.

graph -T tek , which producesoutputfor a Tektronixterminalor emulator, checkstheTERMenvironmentvariable. If the value of TERMis a string beginning with " xterm" , " nxterm" , or" kterm" , it is taken as a sign that graph is running in an X Window SystemVT100 terminalemulator:anxterm , nxterm , or kterm . Beforedrawing graphics,graph -T tek will emitanescapesequencethatcausestheterminalemulator’s auxiliaryTektronixwindow, which is normallyhidden,to popup. After the graphicsaredrawn, an escapesequencethat returnscontrol to theoriginal VT100window will beemitted.TheTektronixwindow will remainon thescreen.

If thevalueof TERMis astringbeginningwith " kermit" , " ansi.sys" , or " nansi.sys" , it is takenasasignthatgraph is runningin theVT100terminalemulatorprovidedby theMS-DOSversionofkermit . Beforedrawing graphics,graph -T tek will emitanescapesequencethatswitchestheterminalemulatorto Tektronixmode.Also, someof theTektronixcontrolcodesemittedby graph-T tek will be kermit -specific. Therewill be a limited amountof color support,which is notnormally thecase(the16 ansi.sys colorswill be supported).After drawing graphics,graph-T tek will emit anescapesequencethatreturnstheemulatorto VT100 mode.Thekey sequence‘ALT minus’ canbeemployedmanuallywithin kermit to switchbetweenthetwo modes.

Page 32: plotutils

Chapter3: Theplot Program 27

3 The plot Program

3.1 How to useplot

TheGNU plot filter plot displaysGNU graphicsmetafilesor translatesthemto otherformats.It will takeinputfrom filesspecifiedonthecommandlineor from standardinput. The‘ -T ’ optionisusedto specifythedesiredoutputformat. Supportedoutputformatsinclude" X" , " png" , " pnm" ," gif" , " svg" , " ai" , " ps" , " cgm" , " fig" , " pcl" , " hpgl" , " regis" , " tek" , and" meta" (thedefault).

Themetafileformat is a device-independentformat for storageof vectorgraphics.By default,it is a binary ratherthana human-readableformat (seeAppendixD [Metafiles],page158). Eachof thegraph , pic2plot , tek2plot , andplotfont utilities will write a graphicsmetafiletostandardoutputif no ‘ -T ’ option is specifiedon its commandline. TheGNU libplot graphicslibrary may alsobe usedto producemetafiles. Metafilesmay containarbitrarily many pagesofgraphics,but eachmetafileproducedby graph containsonly asinglepage.

plot , like themetafileformatitself, is usefulif youwish to preserve avectorgraphicsfile, anddisplayor edit it with morethanonedrawing editor. The following exampleshows how you maydo this.

To producea plot of dataarrangedasalternating9 and : coordinatesin anASCII file, youmayusegraph asfollows:

graph < datafile > test.meta

The file ‘ test.meta ’ will be a single-pagegraphicsmetafile. Similarly, to createin metafileformataplot consistingof asimplefigure,youmaydo:

echo 0 0 1 1 2 0 | spline | graph > test.meta

To displayany suchplot on anX Window Systemdisplay, youwoulddo

plot -T X test.meta

or

plot -T X < test.meta

To print theplot on aPostscriptprinter, youwoulddo somethinglike

plot -T ps < test.meta | lpr

To edit it with thefree idraw drawing editor, youwoulddo

plot -T ps < test.meta > test.psidraw test.ps

To produceaPNGfile, youwoulddo

plot -T png < test.meta > test.png

Toproducea“portableanymap”(afile in PBM,PGM,orPPMformat,whicheverismostappropriate)youwoulddo

plot -T pnm < test.meta > test.pnm

andto produceapseudo-GIFfile, youwoulddo

plot -T gif < test.meta > test.gif

Similarly, to produceversionsof theplot in SVG formatandWebCGMformatthatcanbedisplayedin a Webbrowserwith SVG andWebCGMsupport,youwoulddo

Page 33: plotutils

Chapter3: Theplot Program 28

plot -T svg < test.meta > test.svgplot -T cgm < test.meta > test.cgm

To produceaversionof theplot thatcanbeviewedandeditedwith AdobeIllustrator, youwoulddo

plot -T ai < test.meta > test.ai

andto producea versionthat canbe viewed andeditedwith the free xfig drawing editor, youwoulddo

plot -T fig < test.meta > test.figxfig test.fig

Otherformatsmay be obtainedby usingplot -T pcl , plot -T hpgl , plot -T regis , andplot -T tek .

plot maybehavedifferentlydependingontheenvironmentin whichit is invoked. In particular,plot -T svg , plot -T ai , plot -T ps , plot -T cgm, plot -T fig , plot -T pcl , andplot -T hpgl areaffectedby theenvironmentvariablePAGESIZE. plot -T X, plot -T png ,plot -T pnm, andplot -T gif areaffectedby the environmentvariableBITMAPSIZE . TheDISPLAY environmentvariableaffects the operationof plot -T X, andthe TERMenvironmentvariableaffectstheoperationof plot -T tek . Therearealsoseveralenvironmentvariablesthataffect theoperationof plot -T pcl andplot -T hpgl . For acompletediscussionof theeffectsof theenvironmenton plot , seeSection3.3 [plot Environment],page33.

3.2 plot command-lineoptions

Theplot filter plot translatesGNU graphicsmetafilesto otherformats.The‘ -T ’ optionis usedto specifytheoutputformator displaytype. Filesin metafileformatareproducedby GNU graph ,pic2plot , tek2plot , plotfont , andotherapplicationsthatusetheGNU libplot graphicslibrary. For technicaldetailson themetafileformat,seeAppendixD [Metafiles],page158.

Input file namesmaybespecifiedanywhereon thecommandline. That is, therelative orderoffile namesandcommand-lineoptionsdoesnot matter. If no files arespecified,or thefile name‘ - ’is specified,thestandardinput is read. An outputfile is written to standardoutput,unlessthe ‘ -TX’ optionis specified.In thatcasetheoutputis displayedin awindow or windowsonanX WindowSystemdisplay, andthereis no outputfile.

Thefull setof command-lineoptionsis listedbelow. Therearefour sortsof option:

1. Optionssettingthevaluesof drawing parameters.

2. Optionsrelevant only to raw plot , i.e., relevant only if no displaytype or output format isspecifiedwith the‘ -T ’ option.

3. Optionsspecifyingthetypeof metafileformattheinput is in (for backwardcompatibilityonly).

4. Optionsrequestinginformation(e.g.,‘ --help ’).

Eachoptionthattakesanargumentis followed,in parentheses,by thetypeanddefault valueof theargument.

Thefollowing optionssetthevaluesof drawing parameters.

‘ -T type’‘ --display-type type’

(String,default " meta" .) Selecta displaytype or outputformat of type type, whichmaybe oneof thestrings" X" , " png" , " pnm" , " gif" , " svg" , " ai" , " ps" , " cgm" ,

Page 34: plotutils

Chapter3: Theplot Program 29

" fig" , " pcl" , " hpgl" , " regis" , " tek" , and" meta" . Theserefer respectively to theX Window System, PNGformat,portableanymap(PBM/PGM/PPM)format,pseudo-GIF format,thenew XML-basedScalableVectorGraphicsformat,theformatusedbyAdobeIllustrator, idraw -editablePostscript,theWebCGMformatfor Web-basedvec-tor graphics,theformatusedby thexfig drawing editor, theHewlett–PackardPCL 5printerlanguage,theHewlett–PackardGraphicsLanguage(by default, HP-GL/2),theReGIS(remotegraphicsinstructionset)formatdevelopedby DEC, Tektronixformat,anddevice-independentGNU graphicsmetafileformat.

‘ -p n’‘ --page-number n’

(Positive integer.) Display only pagenumbern, within the metafileor sequenceofmetafilesthatis beingtranslated.

Metafilesmayconsistof oneor morepages,numberedbeginningwith 1. Also, eachpagemaycontainmultiple‘frames’. plot -T X, plot -T regis , orplot -T tek ,which plot in real time, will separatesuccessive framesby screenerasures.plot -T png , plot -T pnm, plot -T gif , plot -T svg , plot -T ai , plot -T ps ,plot -T cgm, plot -T fig , plot -T pcl , plot -T hpgl , which do notplot inrealtime,will displayonly thelastframeof any multi-framepage.

Thedefault behavior, if ‘ -p ’ is not used,is to displayall pages.For example,plot-T X displayseachpagein its own X window. If the‘ -T png ’ option,the‘ -T pnm’option,the‘ -T gif ’ option,the‘ -T svg ’ option,the‘ -T ai ’ option,or the‘ -T fig ’optionis used,thedefault behavior is to displayonly thefirst page,sincefiles in PNG,PNM,pseudo-GIF, SVG,AI, or Fig formatmaycontainonly asinglepageof graphics.

Most metafilesproducedby theGNU plotting utilities (e.g.,by raw graph ) containonly a singlepage,consistingof two frames:anemptyoneto clearthedisplay, andasecondonecontaininggraphics.

‘ -s ’‘ --merge-pages ’

Mergeall displayedpagesinto a singlepage,andalsomergeall ‘frames’ within eachdisplayedpage.

This optionis usefulwhenmerging togethersingle-pageplotsfrom differentsources.For example,it canbeusedto mergetogetherplotsobtainedfrom separateinvocationsof graph . Thisis analternative form of multiplotting(seeSection2.4[Multiplotting],page11).

‘ --bitmap-size bitmapsize’(String,default " 570x570" .) Setthesizeof thegraphicsdisplayin whichtheplot willbedrawn, in termsof pixels, to bebitmapsize. This is relevant only to plot -T X,plot -T png , plot -T pnm, andplot -T gif , for all of which the sizecanbeexpressedin termsof pixels. The environmentvariableBITMAPSIZE may equallywell beusedto specifythesize.

Thegraphicsdisplayusedby plot -T X is a popped-upX window. Command-linepositioningof thiswindow onanX Window Systemdisplayissupported.Forexample,if bitmapsizeis " 570x570+0+0" thenthewindow will bepoppedupin theupperleftcorner.

Page 35: plotutils

Chapter3: Theplot Program 30

If youchoosearectangular(non-square)window size,thefontsin theplotwill bescaledanisotropically, i.e., by different factorsin the horizontalandvertical direction. Forthis, plot -T X requiresanX11R6display. Any font thatcannotbeanisotropicallyscaledwill be replacedby a default scalablefont, suchas the Hershey vector font" HersheySerif" .

For backwardcompatibility, plot -T Xallowstheuserto setthewindow sizeandpo-sition by settingtheX resourceXplot.geometry , insteadof ‘ --bitmap-size ’or BITMAPSIZE .

‘ --emulate-color option’(String, default " no" .) If option is " yes" , replaceeachcolor in the output by anappropriateshadeof gray. This is seldomuseful,exceptwhenusing‘plot -T pcl ’to prepareoutput for a PCL5 device. (Many monochromePCL 5 devices, suchasmonochromeLaserJets,do a poor job of emulatingcolor on their own. They usuallymapHP-GL/2’ssevenstandardpencolors,includingevenyellow, to black.) Youmayequallywell requestcolor emulationby settingtheenvironmentvariableEMULATE_COLORto " yes" .

‘ --max-line-leng th max line length’(Integer, default 500.) Setthemaximumnumberof pointsthata polygonalline maycontain,beforeit is flushedto the output device, to equalmax line length. If thisflushing occurs,the polygonalline will be split into two or moresub-lines,thoughthe splitting shouldnot be noticeable.Splitting will not take placeif the line is theboundaryof afilled polygon.

The reasonfor splitting long polygonallines is that somedisplaydevices (e.g.,oldPostscriptprintersandHP-GLpenplotters)havelimitedbuffer sizes.TheenvironmentvariableMAX_LINE_LENGTHcanalsobeusedto specifythemaximumline length.Thisoptionhasnoeffectonplot -T tek or raw plot , sincethey draw polylinesinrealtimeandhave nobuffer limitations.

‘ --page-size pagesize’(String,default " letter" .) Setthesizeof thepageonwhichtheplot will bepositioned.This is relevant only to plot -T svg , plot -T ai , plot -T ps , plot -T cgm,plot -T fig , plot -T pcl , and plot -T hpgl . " letter" meansan 8.5in by11in page. Any ISO pagesizein the range" a0" . . . " a4" or ANSI pagesizein therange" a" . . . " e" maybespecified(" letter" is analiasfor " a" and" tabloid" is analias for " b" ). " legal" , " ledger" , and" b5" are recognizedpagesizesalso. TheenvironmentvariablePAGESIZEcanequallywell beusedto specifythepagesize.

For plot -T ai , plot -T ps , plot -T pcl , andplot -T fig , thegraphicsdis-play (or ‘viewport’) within which theplot is drawn will be,by default,asquareregioncenteredon thespecifiedpage.For plot -T hpgl , it will bea squareregion of thesamesize,but maybepositioneddifferently. Eitheror bothof thedimensionsof thegraphicsdisplaycanbespecifiedexplicitly. For example,pagesizecouldbespecifiedas" letter,xsize=4in" , or " a4,xsize=10cm,ysize=15cm" . Thedimensionsareallowedto benegative (a negative dimensionresultsin a reflection).

The positionof the graphicsdisplay, relative to its default position,may optionallybeadjustedby specifyinganoffset vector. For example,pagesizecouldbespecifiedas " letter,yoffset=1.2in" , or " a4,xoffset=; 5mm,yoffset=2.0cm" . It is alsopossible

Page 36: plotutils

Chapter3: Theplot Program 31

to positionthe graphicsdisplayprecisely, by specifyingthe locationof its lower leftcornerrelative to the lower left cornerof the page. For example,pagesizecould bespecifiedas" letter,xorigin=2in,yorigin=3in" , or " a4,xorigin=0.5cm,yorigin=0.5cm" .Theprecedingoptionsmaybeintermingled.plot -T svg andplot -T cgm ignorethe " xoffset" , " yoffset" , " xorigin" , and " yorigin" options,sinceSVG format andWebCGMformathave no notionof theWebpageon which thegraphicsdisplaywillultimatelybepositioned.For moreonpagesizes,seeAppendixC [PageandViewportSizes],page156.

Thefollowing optionssettheinitial valuesof additionaldrawing parameters.Any of thesemaybeoverriddenby adirective in themetafileitself. In fact, theseoptionsareusefulonly whenplottingold metafilesin thepre-GNU‘plot(5)’ format,whichdid not includesuchdirectives.

‘ --bg-color name’(String,default " white" .) Setthecolorusedfor theplot backgroundto bename. Thisis relevantonly to plot -T X, plot -T png , plot -T pnm, plot -T gif , plot-T cgm, plot -T regis , andplot -Tmeta . An unrecognizednamesetsthecolorto thedefault. For informationonwhatnamesarerecognized,seeAppendixB [ColorNames],page155. TheenvironmentvariableBG_COLORcanequallywell beusedtospecifythebackgroundcolor.

If the ‘ -T png ’ or ‘ -T gif ’ option is used,a transparentPNG file or a transparentpseudo-GIF, respectively, may be producedby settingthe TRANSPARENT_COLORenvironment variable to the nameof the backgroundcolor. SeeSection3.3 [plotEnvironment],page33. If the ‘ -T svg ’ or ‘ -T cgm’ option is used,an outputfilewithout abackgroundmaybeproducedby settingthebackgroundcolor to " none" .

‘ -f font size’‘ --font-size font size’

(Float,initial valuedevice-dependent.)Settheinitial sizeof thefontusedfor renderingtext, asa fractionof thewidth of thegraphicsdisplay, to font size.

‘ -F font name’‘ --font-name font name’

(String, default " Helvetica" except for plot -T pcl , for which " Univers" is thedefault, andplot -T png , plot -T pnm, plot -T gif , plot -T hpgl , plot-T regis , plot -T tek , and raw plot , for all of which " HersheySerif" is thedefault.) Setthefont initially usedfor text (i.e., for ‘labels’) to font name. Fontnamesarecase-insensitive. If thespecifiedfont is notavailable,thedefault font will beused.Which fonts are available dependson which ‘ -T ’ option is used. For a list of allfonts,seeSectionA.1 [Text Fonts],page134. Theplotfont utility will produceacharactermapof any availablefont. SeeChapter6 [plotfont], page51.

‘ -W line width’‘ --line-width line width’

(Float,default < 1.0.) Setthethicknessof lines,asafractionof thesize(i.e.,minimumdimension)of the graphicsdisplay, to line width. A negative value meansthat thedefault valueprovided by theGNU libplot graphicslibrary shouldbeused.Thisis usually1/850timesthesizeof thedisplay, althoughif ‘ -T X’, ‘ -T png ’, ‘ -T pnm’,or ‘ -T gif ’ is specified,it is zero.By convention,azero-thicknessline is thethinnest

Page 37: plotutils

Chapter3: Theplot Program 32

line thatcanbedrawn. This is thecasein all outputformats.Note,however, that thedrawing editorsidraw andxfig treatzero-thicknesslinesasinvisible.

plot -T tek andplot -T regis do not supportdrawing lines with otherthanadefault thickness,andplot -T hpgl doesnot supportdoingso if the environmentvariableHPGL_VERSIONis setto avaluelessthan" 2" (thedefault).

‘ --pen-color name’(String,default " black" .) Setthepencolor to bename. An unrecognizednamesetsthepencolor to thedefault. For informationon whatcolor namesarerecognized,seeAppendixB [Color Names],page155.

Thefollowing optionis relevantonly to raw plot , i.e.,relevantonly if nooutputtypeisspecifiedwith the ‘ -T ’ option. In this caseplot outputsa graphicsmetafile,which may be translatedtootherformatsby asecondinvocationof plot .

‘ -O ’‘ --portable-outp ut ’

Outputtheportable(human-readable)versionof GNU metafileformat, ratherthanabinary version(the default). This canalsobe requestedby settingthe environmentvariableMETA_PORTABLEto " yes" .

plot will automaticallydeterminewhich typeof GNU metafileformat the input is in. Therearetwo types: binary(thedefault) andportable(human-readable).Thebinary format is machine-dependent.SeeAppendixD [Metafiles],page158.

For compatibilitywith olderplottingsoftware,thereadingof inputfilesin thepre-GNU‘plot(5)’format is also supported. This is normally a binary format, with eachinteger in the metafilerepresentedasa pair of bytes.Theorderof thetwo bytesis machinedependent.You mayspecifythat input file(s) arein plot(5) formatratherthanordinaryGNU metafileformatby usingeitherthe‘ -h ’ option(“high bytefirst”) or the‘ -l ’ option(“low bytefirst”), whichever is appropriate.Somenon-GNUsystemssupportanASCII (human-readable)variantof plot(5) format. You mayspecifythat theinput is in this formatby usingthe‘ -A ’ option. Irrespective of thevariant,a file in plot(5)formatincludesonly onepageof graphics.

‘ -h ’‘ --high-byte-fir st- in put ’

Input file(s) areassumedto be in traditional‘plot(5)’ metafileformat,with thehigh-orderbyteof eachintegeroccurringfirst. This variantis uncommon.

‘ -l ’‘ --low-byte-firs t-i nput ’

Inputfile(s)areassumedtobeintraditional ‘plot(5)’ metafileformat,with thelow-orderbyteof eachintegeroccurringfirst. Thisvariantis themostcommon.

‘ -A ’‘ --ascii-input ’

Input file(s) areassumedto be in the ASCII variantof traditional ‘plot(5)’ metafileformat. Thisvariantis rare:onsomeoldersystems,it is producedby aprogramcalledplottoa .

Thefollowing optionsrequestinformation.

‘ --help ’ Print a list of command-lineoptions,andthenexit.

Page 38: plotutils

Chapter3: Theplot Program 33

‘ --help-fonts ’Print a tableof availablefonts,andthenexit. Thetablewill dependon which displaytypeor outputformat is specifiedwith the ‘ -T ’ option. plot -T X, plot -T svg ,plot -T ai , plot -T ps , plot -T cgm, andplot -T fig eachsupportthe 35standardPostscriptfonts. plot -T svg , plot -T ai , plot -T pcl , andplot -Thpgl supportthe45 standardPCL 5 fonts, andplot -T pcl andplot -T hpglsupporta numberof Hewlett–Packardvector fonts. All of the preceding,togetherwith plot -T png , plot -T pnm, plot -T gif , plot -T regis , andplot -Ttek , supporta setof 22 Hershey vectorfonts. Raw plot in principlesupportsanyof thesefonts, sinceits outputmustbe translatedto other formatswith plot . Theplotfont utility will producea charactermapof any availablefont. SeeChapter6[plotfont], page51.

‘ --list-fonts ’Like ‘ --help-fonts ’, but lists the fonts in a singlecolumnto facilitatepiping tootherprograms.If no displaytypeor outputformat is specifiedwith the‘ -T ’ option,thefull setof supportedfontsis listed.

‘ --version ’Print theversionnumberof plot andtheplotting utilities package,andexit.

3.3 Environmentvariables

The behavior of plot is affected by several environment variables. We have alreadymentioned the environment variables BITMAPSIZE , PAGESIZE, BG_COLOR, EMULATE_COLOR, MAX_LINE_LENGTH, and ROTATION. They serve as backups for the severaloptions ‘ --bitmap-size ’, ‘ --page-size ’, ‘ --bg-color ’, ‘ --emulate-colo r ’,‘ --max-line-leng th ’, and ‘ --rotation ’. The remaining environment variables arespecificto individual outputformats.

plot -T X, whichpopsupawindow onanX Window Systemdisplayanddrawsgraphicsin it,checksthe DISPLAY environmentvariable. The valueof this variabledeterminesthe displayonwhich thewindow will bepoppedup.

plot -T png andplot -T gif , whichproduceoutputin PNGformatandpseudo-GIFformatrespectively, areaffectedby two environmentvariables. If thevalueof the INTERLACEvariableis " yes" , the output file will be interlaced. Also, if the value of the TRANSPARENT_COLORenvironmentvariableis thenameof acolor thatappearsin theoutputfile, thatcolor will betreatedas transparentby most applications. For information on what color namesare recognized,seeAppendixB [Color Names],page155.

plot -T pnm, whichproducesoutputin PortableAnymap(PBM/PGM/PPM)format,isaffectedby thePNM_PORTABLEenvironmentvariable. If its valueis " yes" , theoutputfile will be in theportable(humanreadable)versionof PBM, PGM, or PPMformat,ratherthanthedefault (binary)version.

plot -T cgm, which producesCGM files that comply with the WebCGM profile for Web-basedvectorgraphics,is affectedby two environmentvariables.By default,aversion3 CGM file isgenerated.Many olderCGM interpretersandviewers,suchastheonesbuilt into Microsoft Officeand other commercialsoftware, only supportversion1 CGM files. The CGM_MAX_VERSIONenvironmentvariablemay be set to " 1" , " 2" , " 3" , or " 4" (the default) to specifya maximum

Page 39: plotutils

Chapter3: Theplot Program 34

valuefor theversionnumber. TheCGM_ENCODINGvariablemayalsobeset,to specifythe typeof encodingusedin the CGM file. Supportedvaluesare" clear text" (i.e., humanreadable)and" binary" (thedefault). TheWebCGMprofile requiresthatthebinaryencodingbeused.

plot -T pcl , which producesPCL5 outputfor Hewlett–Packardprinters,is affectedby theenvironmentvariablePCL_ASSIGN_COLORS. It shouldbesetto " yes" whenproducingPCL 5output for a color printer or othercolor device. This will ensureaccuratecolor reproductionbygiving theoutputdevice completefreedomin assigningcolors,internally, to its “logical pens”. Ifit is " no" then the device will usea fixed setof coloredpens,andwill emulateothercolorsbyshading.Thedefault is " no" becausemonochromePCL 5 devices,which aremorecommonthancoloredones,mustuseshadingto emulatecolor.

plot -T hpgl , which producesHewlett–PackardGraphicsLanguageoutput,is alsoaffectedby several environmentvariables. The most importantis HPGL_VERSION, which may be setto" 1" , " 1.5" , or " 2" (thedefault). " 1" meansthattheoutputshouldbegenericHP-GL," 1.5" meansthattheoutputshouldbesuitablefor theHP7550AgraphicsplotterandtheHP758x,HP7595AandHP7596Adraftingplotters(HP-GLwith someHP-GL/2extensions),and" 2" meansthattheoutputshouldbe modernHP-GL/2. If the versionis " 1" or " 1.5" thenthe only available fonts will bevectorfonts,andall lines will be drawn with a default thickness(the ‘ -W’ option will not work).Additionally, if the versionis " 1" thenthe filling of arbitrarycurveswith solid color will not besupported(circlesandrectanglesalignedwith thecoordinateaxesmaybefilled, though).

The position of the plot -T hpgl graphicsdisplay on the pagecan be rotated90 degreescounterclockwiseby settingthe HPGL_ROTATEenvironmentvariableto " yes" . This is not thesameasthe rotationobtainedwith the ‘ --rotation ’ option, sinceit both rotatesthe graphicsdisplayandrepositionsits lower left cornertowardanothercornerof thepage.Besides" no" and" yes" , recognizedvaluesfor the HPGL_ROTATEvariableare " 0" , " 90" , " 180" , and" 270" ." no" and" yes" areequivalent to " 0" and" 90" , respectively. " 180" and" 270" aresupportedonly if HPGL_VERSIONis " 2" (thedefault).

Opaquefilling andthe drawing of visible white lines aresupportedonly if HPGL_VERSIONis " 2" (the default) andthe environmentvariableHPGL_OPAQUE_MODEis " yes" (the default).If thevalueis " no" thenopaquefilling will notbeused,andwhitelines(if any), whicharenormallydrawn with pen#0, will not be drawn. This featureis to accommodateolder HP-GL/2 devices.HP-GL/2penplotters,for example, donotsupportopacityor theuseof pen#0to draw visiblewhitelines. SomeolderHP-GL/2devicesreportedlymalfunctionif askedto draw opaqueobjects.

By default, plot -T hpgl will draw with a fixed setof pens. Which pensarepresentmaybe specifiedby settingthe HPGL_PENSenvironmentvariable. If HPGL_VERSIONis " 1" , thedefault valueof HPGL_PENSis " 1=black" ; if HPGL_VERSIONis " 1.5" or " 2" , thedefault valueof HPGL_PENSis " 1=black:2=red:3=green:4=yellow:5=blue:6=magenta:7=cyan" . The formatshouldbe self-explanatory. By settingHPGL_PENS, you may specifya color for any penin therange#1. . .#31. For informationon what color namesare recognized,seeAppendix B [ColorNames],page155. Pen#1 mustalwaysbepresent,thoughit neednot beblack. Any otherpenintherange#1. . .#31maybeomitted.

If HPGL_VERSIONis " 2" then plot -T hpgl will also be affected by the environmentvariableHPGL_ASSIGN_COLORS. If thevalueof thisvariableis " yes" , thenplot -T hpgl willnotberestrictedto thepalettespecifiedin HPGL_PENS: it will assigncolorsto “logical pens”in therange#1. . .#31,asneeded. Thedefault valueis " no" becauseotherthancolor LaserJetprintersandDesignJetplotters,not many HP-GL/2devicesallow theassignmentof colorsto logical pens.In particular, HP-GL/2penplottersdo not.

Page 40: plotutils

Chapter3: Theplot Program 35

plot -T tek , which producesoutputfor a Tektronix terminalor emulator, checkstheTERMenvironmentvariable. If the value of TERMis a string beginning with " xterm" , " nxterm" , or" kterm" , it is taken as a sign that plot is running in an X Window SystemVT100 terminalemulator:anxterm , nxterm , or kterm . Beforedrawing graphics,plot -T tek will emit anescapesequencethatcausestheterminalemulator’s auxiliaryTektronixwindow, which is normallyhidden,to popup. After the graphicsaredrawn, an escapesequencethat returnscontrol to theoriginal VT100window will beemitted.TheTektronixwindow will remainon thescreen.

If thevalueof TERMis astringbeginningwith " kermit" , " ansi.sys" , or " nansi.sys" , it is takenasa sign thatplot is runningin theVT100 terminalemulatorprovided by theMS-DOSversionof kermit . Beforedrawing graphics,plot -T tek will emit anescapesequencethat switchesthe terminalemulatorto Tektronix mode. Also, someof the Tektronix control codesemittedbyplot -T tek will bekermit -specific.Therewill bea limited amountof colorsupport,which isnotnormallythecase(the16ansi.sys colorswill besupported).After drawing graphics,plot-T tek will emit anescapesequencethatreturnstheemulatorto VT100 mode.Thekey sequence‘ALT minus’ canbeemployedmanuallywithin kermit to switchbetweenthetwo modes.

Page 41: plotutils

Chapter4: Thepic2plot Program 36

4 The pic2plot Program

4.1 What pic2plot is usedfor

The pic2plot programtakesoneor morefiles in the pic language,andeitherdisplaysthefiguresthatthey containon anX Window Systemdisplay, or producesanoutputfile containingthefigures.Many graphicsfile formatsaresupported.

Thepic languageis a ‘little language’thatwasdevelopedat Bell Laboratoriesfor creatingbox-and-arrow diagramsof the kind frequentlyfound in technicalpapersandtextbooks. A directorycontainingdocumentationonthepic languageisdistributedalongwith theplottingutilities. On mostsystemsit is installedas‘ /usr/share/pic2 plo t ’ or ‘ /usr/local/share /p ic 2plo t ’.The directory includesBrian Kernighan’s original technicalreporton the language,Eric S. Ray-mond’s tutorial on theGNU implementation,andsomesamplepic macroscontributedby the lateW. RichardStevens.

The pic languagewas originally designedto work with the troff documentformatter. Inthat context it is readby a translatorcalledpic , or its GNU counterpartgpic . Sinceextensivedocumentationonpic andgpic is available,thissectionsimplygivesanexampleof aninputfile,andmentionssomeextra featuressupportedby pic2plot .

A pic file containsoneor morefigures,eachof thebox-and-arrow type. Eachfigureis begunbya line reading.PS , andendedby a line reading.PE . Linesthatarenotcontainedin a .PS . . . .PEpair areignored. Eachfigure is built from geometricalobjects,suchasrectangularboxes,circles,ellipses,quartercircles(“arcs”), polygonallines,andsplines.Arcs,polygonallines,andsplinemaybeequippedwith arrowheads.Any objectmaybelabeledwith oneor morelinesof text.

Objectsareusuallypositionednotbyspecifyingtheirpositionsin absolutecoordinates,but ratherby specifyingtheir positionsrelative to other, previously drawn objects.Thefollowing figureis anexample.

.PSbox "START"; arrow; circle dashed filled; arrowcircle diam 2 thickness 3 "This is a" "big, thick" "circle" dashed; uparrow from top of last circle; ellipse "loopback" dashedarrow dotted from left of last ellipse to top of last boxarc cw radius 1/2 from top of last ellipse; arrowbox "END".PE

If you put this examplein a file andrun ‘pic2plot -T X’ on the file, a window containingthefigurewill bepoppedup on your X display. Similarly, if you run ‘pic2plot -T ps ’ on thefile,a Postscriptfile containingthefigurewill bewritten to standardoutput. ThePostscriptfile maybeeditedwith the idraw drawing editor. OthergraphicsformatssuchasPNGformat,PNM format,pseudo-GIFformat,SVG format,WebCGMformat,or Fig format(which is editablewith thexfigdrawing editor) may be obtainedsimilarly. You would usethe options‘ -T png ’, ‘ -T pnm’, ‘ -Tgif ’, samp -T svg , ‘ -T cgm’, and‘ -T fig ’, respectively.

Theabove exampleillustratessomeof thefeaturesof thepic language.By default, successiveobjectsaredrawn soasto toucheachother. Thedrawing proceedsin a certaindirection,which atstartupis left-to-right. The‘up ’ commandchangesthis directionto bottom-to-top,sothatthenextobject(thearrow extendingfrom thetopof thebig circle)will pointupwardratherthanto theright.

Page 42: plotutils

Chapter4: Thepic2plot Program 37

Objectshave sizesandotherattributes,which maybesetglobally, or specifiedon a per-objectbasis.For example,thediameterof acirclemaybespecified,or theradiusof anarc. An arcmaybeorientedclockwiseratherthancounterclockwiseby specifyingthe‘cw’ attribute. Theline styleofmostobjectsmaybealteredby specifyingthe ‘dashed ’ or ‘dotted ’ attribute. Also, any objectmaybelabeled,by specifyingoneor moretext stringsasattributes.A text stringmaycontainescapesequencesthatshift thefont,appendsubscriptsor superscripts,or includenon-ASCIIcharactersandmathematicalsymbols.SeeSectionA.4 [Text StringFormat],page141.

Most sizesandpositionsareexpressedin termsof ‘virtual inches’. The useof virtual inchesis peculiarto pic2plot . The graphicsdisplayusedby pic2plot , i.e., its drawing region, isdefinedto beasquare,8 virtual incheswideand8 virtual incheshigh. If thepagesizefor theoutputfile is the " letter" size,which is the default for Postscriptoutput,virtual incheswill the sameasrealinches.But adifferentpagesizemaybespecified;for example,by usingthe‘ --page-sizea4 ’ option. If so, a virtual inch will simply equalone-eighthof thewidth of thegraphicsdisplay.On A4 paper, thegraphicsdisplayis asquareof size19.81cm.

By default, eachfigure is centeredin thegraphicsdisplay. You mayturn off centering,so thatyou canuseabsolutecoordinates,by usingthe ‘ -n ’ option. For example,a figureconsistingonlyof theobject‘arrow from (8,8) to (4,4) ’ will bepositionedin theabsenceof centeringsothattheheadof thearrow is at thecenterof thedisplay. Its tail will beat theupperright corner.

Thethicknessof lines is not specifiedin termsof virtual inches.For compatibilitywith gpic ,it is specifiedin termsof virtual points. The exampleabove, which specifiesthe ‘ thickness ’attributeof oneof theobjects,illustratesthis. Thereare72 virtual pointspervirtual inch.

If thereis morethanonefigureto bedisplayed,they will appearin differentX windows, or onsuccessive pagesof theoutputfile. Someoutputformats(suchasPNG,PNM, pseudo-GIF, SVG,Illustrator, andFig) supportonly asinglepageof graphics.If any of thoseoutputformatsis chosen,only thefirst figurewill appearin theoutputfile. Currently, pic2plot cannotproduceanimatedpseudo-GIFs.

Theprecedingsurvey doesnot do justiceto thepic language,which is actuallya full-featuredprogramminglanguage,with supportfor variables,looping constructs,etc. Its advancedfeaturesmake thedrawing of large,repetitive diagramsquiteeasy.

4.2 pic2plot command-lineoptions

Thepic2plot programtranslatesfilesin thepic language,whichis usedfor creatingbox-and-arrow diagramsof the kind frequentlyfound in technicalpapersandtextbooks,to othergraphicsformats. Theoutputformator displaytype is specifiedwith the ‘ -T ’ option. Thepossibleoutputformatsarethesameformatsthataresupportedby theGNU graph andplot programs.

Input file namesmaybespecifiedanywhereon thecommandline. That is, therelative orderoffile namesandcommand-lineoptionsdoesnot matter. If no files arespecified,or thefile name‘ - ’is specified,thestandardinput is read. An outputfile is written to standardoutput,unlessthe ‘ -TX’ optionis specified.In thatcasetheoutputis displayedin oneor morewindows onanX WindowSystemdisplay, andthereis no outputfile.

Thefull setof command-lineoptionsis listedbelow. Therearethreesortsof option:

1. Generaloptions.

2. Optionsrelevantonly to raw pic2plot , i.e.,relevantonly if nodisplaytypeor outputformatis specifiedwith the‘ -T ’ option.

Page 43: plotutils

Chapter4: Thepic2plot Program 38

3. Optionsrequestinginformation(e.g.,‘ --help ’).

Eachoptionthattakesanargumentis followed,in parentheses,by thetypeanddefault valueof theargument.

Thefollowing aregeneraloptions.

‘ -T type’‘ --display-type type’

(String,default " meta" .) Selecta displaytype or outputformat of type type, whichmaybe oneof thestrings" X" , " png" , " pnm" , " gif" , " svg" , " ai" , " ps" , " cgm" ," fig" , " pcl" , " hpgl" , " regis" , " tek" , and" meta" . Theserefer respectively to theX Window System, PNGformat,portableanymap(PBM/PGM/PPM)format,pseudo-GIF format,thenew XML-basedScalableVectorGraphicsformat,theformatusedbyAdobeIllustrator, idraw -editablePostscript,theWebCGMformatfor Web-basedvec-tor graphics,theformatusedby thexfig drawing editor, theHewlett–PackardPCL 5printerlanguage,theHewlett–PackardGraphicsLanguage(by default, HP-GL/2),theReGIS(remotegraphicsinstructionset)formatdevelopedby DEC, Tektronixformat,anddevice-independentGNU graphicsmetafileformat.

‘ -d ’‘ --precision-das hin g’

Draw dashedanddottedlines carefully, i.e., draw eachdashanddot asa separatelypositionedobject.Thedefault is tousethesupportfor dashedanddottedlinesprovidedby theunderlyinggraphicslibrary, GNU libplot .

This option may produceslightly better-looking dashedanddottedlines. However,it will comeat a price: if an editableoutput file is produced(i.e.,an outputfile inIllustrator, Postscriptor Fig format), it will be difficulty to modify its dashedanddottedlineswith adrawing editor.

‘ -f font size’‘ --font-size font size’

(Float,default 0.0175.)Setthesizeof thefont usedfor renderingtext, asa fractionofthewidth of thegraphicsdisplay, to font size.

‘ -F font name’‘ --font-name font name’

(String, default " Helvetica" except for pic2plot -T pcl , for which " Univers"is the default, and pic2plot -T png , pic2plot -T pnm, pic2plot -T gif ,pic2plot -T hpgl , pic2plot -T regis , pic2plot -T tek , and rawpic2plot , for all of which " HersheySerif" is thedefault.) Setthefont usedfor textto font name. Font namesarecase-insensitive. If the specifiedfont is not available,thedefault font will beused.Which fontsareavailabledependsonwhich ‘ -T ’ optionis used.For a list of all fonts,seeSectionA.1 [Text Fonts],page134. Theplotfontutility will producea charactermapof any available font. SeeChapter6 [plotfont],page51.

‘ -n ’‘ --no-centering ’

Turnoff theautomaticcenteringof eachfigure. If thisoptionis specified,thepositionof theobjectsin eachfiguremaybespecifiedin termsof absolutecoordinates.E.g.,

Page 44: plotutils

Chapter4: Thepic2plot Program 39

‘ line from (0,0) to (4,4) ’ will draw a line segmentfrom thelower left cornerto the centerof the graphicsdisplay, sincethe displaywidth anddisplayheightaredefinedto equal8 virtual inches.

‘ -W line width’‘ --line-width line width’

(Float,default = 1.0.) Setthedefault thicknessof lines,asa fractionof thesize(i.e.,minimumdimension)of thegraphicsdisplay, to line width. A negative valuemeansthatthedefaultvalueprovidedby theGNU libplot graphicslibrary shouldbeused.This is usually1/850timesthesizeof thedisplay, althoughif ‘ -T X’, ‘ -T png ’, ‘ -Tpnm’, or ‘ -T gif ’ is specified,it is zero. By convention,a zero-thicknessline is thethinnestline thatcanbedrawn. This is thecasein all outputformats.Note,however,thatthedrawing editorsidraw andxfig treatzero-thicknesslinesasinvisible.

pic2plot -T hpgl doesnotsupportdrawinglineswith other thanadefault thicknessif the environment variable HPGL_VERSIONis set to a value less than" 2" (thedefault).

‘ --bg-color name’(String, default " white" .) Set the color usedfor the backgroundto be name. Thisis relevant only to pic2plot -T X, pic2plot -T png , pic2plot -T pnm,pic2plot -T gif , pic2plot -T cgm, pic2plot -T regis , andpic2plot-T meta . An unrecognizednamesetsthe color to the default. For informationon what namesare recognized,seeAppendix B [Color Names],page155. TheenvironmentvariableBG_COLORcanequallywell beusedto specifythebackgroundcolor.

If the ‘ -T png ’ or ‘ -T gif ’ option is used,a transparentPNG file or a transparentpseudo-GIF, respectively, may be producedby settingthe TRANSPARENT_COLORenvironmentvariableto thenameof thebackgroundcolor. SeeSection4.3 [pic2plotEnvironment],page42. If the ‘ -T svg ’ or ‘ -T cgm’ option is used,an outputfilewithout abackgroundmaybeproducedby settingthebackgroundcolor to " none" .

‘ --bitmap-size bitmapsize’(String,default " 570x570" .) Setthesizeof thegraphicsdisplayin whichtheplot willbe drawn, in termsof pixels, to be bitmapsize. This is relevant only to pic2plot-T X, pic2plot -T png , pic2plot -T pnm, and pic2plot -T gif , for allof which the size can be expressedin terms of pixels. The environment variableBITMAPSIZE mayequallywell beusedto specifythesize.

Thegraphicsdisplayusedby pic2plot -T X is apopped-upX window. Command-line positioningof this window on an X Window Systemdisplay is supported.Forexample,if bitmap sizeis " 570x570+0+0" thenthewindow will bepoppedup in theupperleft corner.

If youchoosearectangular(non-square)window size,thefontsin theplotwill bescaledanisotropically, i.e.,bydifferentfactorsin thehorizontalandverticaldirection.Forthis,pic2plot -T X requiresanX11R6display. Any font thatcannotbeanisotropicallyscaledwill be replacedby a default scalablefont, suchas the Hershey vector font" HersheySerif" .

Page 45: plotutils

Chapter4: Thepic2plot Program 40

For backward compatibility, pic2plot -T X allows the user to set the windowsize and position by setting the X resource Xplot.geometry , instead of‘ --bitmap-size ’ or BITMAPSIZE .

‘ --emulate-color option’(String, default " no" .) If option is " yes" , replaceeachcolor in the output by anappropriateshadeof gray. This is seldomuseful, except when using ‘pic2plot-T pcl ’ to prepareoutputfor a PCL5 device. (Many monochromePCL5 devices,suchasmonochromeLaserJets,do a poor job of emulatingcolor on their own. TheyusuallymapHP-GL/2’s seven standardpencolors,including even yellow, to black.)You may equally well requestcolor emulationby settingthe environmentvariableEMULATE_COLORto " yes" .

‘ --max-line-leng th max line length’(Integer, default 500.) Setthemaximumnumberof pointsthata polygonalline maycontain,beforeit is flushedto the output device, to equalmax line length. If thisflushingoccurs,thepolygonalline will besplit into two or moresub-lines,thoughthesplitting shouldnotbenoticeable.

The reasonfor splitting long polygonallines is that somedisplaydevices (e.g.,oldPostscriptprintersandHP-GLpenplotters)havelimitedbuffer sizes.TheenvironmentvariableMAX_LINE_LENGTHcanalsobeusedto specifythemaximumline length.Thisoptionhasnoeffecton raw pic2plot , sinceit draws polylinesin realtimeandhasno buffer limitations.

‘ --page-size pagesize’(String,default " letter" .) Setthesizeof thepageonwhichtheplot will bepositioned.This is relevantonly to pic2plot -T svg , pic2plot -T ai , pic2plot -T ps ,pic2plot -T cgm, pic2plot -T fig , pic2plot -T pcl , andpic2plot -Thpgl . " letter" meansan 8.5in by 11in page. Any ISO pagesize in the range" a0" . . . " a4" or ANSI pagesizein therange" a" . . . " e" maybespecified(" letter"is analiasfor " a" and" tabloid" is analiasfor " b" ). " legal" , " ledger" , and" b5" arerecognizedpagesizesalso.TheenvironmentvariablePAGESIZEcanequallywell beusedto specifythepagesize.

For pic2plot -T ai , pic2plot -T ps , pic2plot -T pcl , andpic2plot -T fig , thegraphicsdisplay(or ‘viewport’) within which theplot is drawn will be,bydefault, a squareregion centeredon thespecifiedpage.For pic2plot -T hpgl , itwill bea squareregion of thesamesize,but maybepositioneddifferently. Eitherorbothof thedimensionsof thegraphicsdisplaycanbespecifiedexplicitly. For example,pagesizecould be specifiedas" letter,xsize=4in" , or " a4,xsize=10cm,ysize=15cm" .Thedimensionsareallowedtobenegative(anegativedimensionresultsin areflection).

The positionof the graphicsdisplay, relative to its default position,may optionallybeadjustedby specifyinganoffset vector. For example,pagesizecouldbespecifiedas " letter,yoffset=1.2in" , or " a4,xoffset=> 5mm,yoffset=2.0cm" . It is alsopossibleto positionthe graphicsdisplayprecisely, by specifyingthe locationof its lower leftcornerrelative to the lower left cornerof the page. For example,pagesizecould bespecifiedas" letter,xorigin=2in,yorigin=3in" , or " a4,xorigin=0.5cm,yorigin=0.5cm" .Theprecedingoptionsmaybeintermingled.pic2plot -T svg andpic2plot -Tcgm ignorethe " xoffset" , " yoffset" , " xorigin" , and" yorigin" options,sinceSVG

Page 46: plotutils

Chapter4: Thepic2plot Program 41

formatandWebCGMformathave no notionof theWebpageon which thegraphicsdisplaywill ultimatelybepositioned.For moreon pagesizes,seeAppendixC [PageandViewportSizes],page156.

‘ --pen-color name’(String,default " black" .) Setthepencolor to bename. An unrecognizednamesetsthepencolor to thedefault. For informationon whatcolor namesarerecognized,seeAppendixB [Color Names],page155.

‘ --rotation angle’(Integer, default 0.) Settherotationangleof thegraphicsdisplayto beangledegrees.Recognizedvaluesare0, 90, 180, and270. The rotation is counterclockwise.Theenvironment variableROTATIONcan equally well be usedto specify the rotationangle.

This option is usedfor switchingbetweenportrait andlandscapeorientations.Post-modernistsmayalsofind it useful.

Thefollowing optionis relevantonly to raw pic2plot , i.e., relevantonly if nodisplaytypeoroutputformatis specifiedwith the‘ -T ’ option. In thiscasepic2plot outputsagraphicsmetafile,whichmaybetranslatedto otherformatsby invoking plot .

‘ -O ’‘ --portable-outp ut ’

Outputtheportable(human-readable)versionof GNU metafileformat, ratherthanabinary version(the default). This canalsobe requestedby settingthe environmentvariableMETA_PORTABLEto " yes" .

Thefollowing optionsrequestinformation.

‘ --help ’ Print a list of command-lineoptions,andthenexit.

‘ --help-fonts ’Print a table of available fonts, and then exit. The table will dependon whichdisplay type or output format is specifiedwith the ‘ -T ’ option. pic2plot -T X,pic2plot -T svg , pic2plot -T ai , pic2plot -T ps , pic2plot -T cgm,andpic2plot -T fig eachsupportthe 35 standardPostscriptfonts. pic2plot-T svg , pic2plot -T ai , pic2plot -T pcl , and pic2plot -T hpgl sup-port the45standardPCL 5 fonts,andpic2plot -T pcl andpic2plot -T hpglsupporta numberof Hewlett–Packardvector fonts. All of the preceding,togetherwith pic2plot -T png , pic2plot -T pnm, pic2plot -T gif , pic2plot -T regis , andpic2plot -T tek , supporta setof 22 Hershey vector fonts. Rawpic2plot in principlesupportsany of thesefonts,sinceits outputmustbetranslatedto otherformatswith plot . Theplotfont utility will producea charactermapofany availablefont. SeeChapter6 [plotfont], page51.

‘ --list-fonts ’Like ‘ --help-fonts ’, but lists the fonts in a singlecolumnto facilitatepiping tootherprograms.If no displaytypeor outputformat is specifiedwith the‘ -T ’ option,thefull setof supportedfontsis listed.

‘ --version ’Print theversionnumberof pic2plot andtheplotting utilities package,andexit.

Page 47: plotutils

Chapter4: Thepic2plot Program 42

4.3 Environmentvariables

The behavior of pic2plot is affected by several environment variables. We havealready mentioned the environment variables BITMAPSIZE , PAGESIZE, BG_COLOR,EMULATE_COLOR, MAX_LINE_LENGTH, andROTATION. They serveasbackupsfor theseveraloptions ‘ --bitmap-size ’, ‘ --page-size ’, ‘ --bg-color ’, ‘ --emulate-colo r ’,‘ --max-line-leng th ’, and ‘ --rotation ’. The remaining environment variables arespecificto individual outputformats.

pic2plot -T X, which popsup a window on an X Window Systemdisplayfor eachfigure,checksthe DISPLAY environmentvariable. The valueof this variabledeterminesthe displayonwhich thewindows will bepoppedup.

pic2plot -T png andpic2plot -T gif , whichproduceoutputin PNGformatandpseudo-GIF formatrespectively, areaffectedby two environmentvariables.If thevalueof theINTERLACEvariableis " yes" , the outputfile will be interlaced. Also, if the value of the TRANSPARENT_COLORenvironmentvariableis thenameof acolor thatappearsin theoutputfile, thatcolorwill betreatedastransparentby mostapplications.For informationon whatcolor namesarerecognized,seeAppendixB [Color Names],page155.

pic2plot -T pnm, which producesoutputin PortableAnymap(PBM/PGM/PPM)format,isaffectedby the PNM_PORTABLEenvironmentvariable. If its valueis " yes" , the outputfile willbein theportable(humanreadable)versionof PBM, PGM,or PPMformat,ratherthanthedefault(binary)version.

pic2plot -T cgm, whichproducesCGMfilesthatcomplywith theWebCGMprofilefor Web-basedvectorgraphics,is affectedby two environmentvariables.By default,aversion3 CGM file isgenerated.Many olderCGM interpretersandviewers,suchastheonesbuilt into Microsoft Officeand other commercialsoftware, only supportversion1 CGM files. The CGM_MAX_VERSIONenvironmentvariablemay be set to " 1" , " 2" , " 3" , or " 4" (the default) to specifya maximumvaluefor theversionnumber. TheCGM_ENCODINGvariablemayalsobeset,to specifythe typeof encodingusedin the CGM file. Supportedvaluesare" clear text" (i.e., humanreadable)and" binary" (thedefault). TheWebCGMprofile requiresthatthebinaryencodingbeused.

pic2plot -T pcl , which producesPCL 5 output for Hewlett–Packardprinters,is affectedby theenvironmentvariablePCL_ASSIGN_COLORS. It shouldbesetto " yes" whenproducingPCL5 outputfor a colorprinteror othercolor device. This will ensureaccuratecolor reproductionby giving theoutputdevice completefreedomin assigningcolors,internally, to its “logical pens”.If it is " no" thenthedevice will usea fixedsetof coloredpens,andwill emulateothercolorsbyshading.Thedefault is " no" becausemonochromePCL 5 devices,which aremorecommonthancoloredones,mustuseshadingto emulatecolor.

pic2plot -T hpgl , which producesHewlett–PackardGraphicsLanguageoutput, is alsoaffectedby several environmentvariables. The most importantis HPGL_VERSION, which maybe setto " 1" , " 1.5" , or " 2" (thedefault). " 1" meansthat theoutputshouldbe genericHP-GL," 1.5" meansthat theoutputshouldbesuitablefor theHP7550AgraphicsplotterandtheHP758x,HP7595AandHP7596Adraftingplotters(HP-GLwith someHP-GL/2extensions),and" 2" meansthat theoutputshouldbemodernHP-GL/2. If theversionis " 1" or " 1.5" thentheonly availablefontswill bevectorfonts,andall lineswill bedrawn with a default thickness(the‘ -W’ optionwillnotwork). Additionally, if theversionis " 1" thenthefilling of arbitrarycurveswith solidcolorwillnotbesupported(circlesandrectanglesalignedwith thecoordinateaxesmaybefilled, though).

Page 48: plotutils

Chapter4: Thepic2plot Program 43

Thepositionof thepic2plot -T hpgl graphicsdisplayonthepagecanberotated90 degreescounterclockwiseby settingthe HPGL_ROTATEenvironmentvariableto " yes" . This is not thesameasthe rotationobtainedwith the ‘ --rotation ’ option, sinceit both rotatesthe graphicsdisplayandrepositionsits lower left cornertowardanothercornerof thepage.Besides" no" and" yes" , recognizedvaluesfor the HPGL_ROTATEvariableare " 0" , " 90" , " 180" , and" 270" ." no" and" yes" areequivalent to " 0" and" 90" , respectively. " 180" and" 270" aresupportedonly if HPGL_VERSIONis " 2" (thedefault).

Opaquefilling andthe drawing of visible white lines aresupportedonly if HPGL_VERSIONis " 2" (the default) andthe environmentvariableHPGL_OPAQUE_MODEis " yes" (the default).If thevalueis " no" thenopaquefilling will notbeused,andwhitelines(if any), whicharenormallydrawn with pen#0, will not be drawn. This featureis to accommodateolder HP-GL/2 devices.HP-GL/2penplotters,for example, donotsupportopacityor theuseof pen#0to draw visiblewhitelines. SomeolderHP-GL/2devicesreportedlymalfunctionif askedto draw opaqueobjects.

By default, pic2plot -T hpgl will draw with a fixed setof pens. Which pensarepresentmaybespecifiedby settingtheHPGL_PENSenvironmentvariable.If HPGL_VERSIONis " 1" , thedefault valueof HPGL_PENSis " 1=black" ; if HPGL_VERSIONis " 1.5" or " 2" , thedefault valueof HPGL_PENSis " 1=black:2=red:3=green:4=yellow:5=blue:6=magenta:7=cyan" . The formatshouldbe self-explanatory. By settingHPGL_PENS, you may specifya color for any penin therange#1. . .#31. For informationon what color namesare recognized,seeAppendix B [ColorNames],page155. Pen#1 mustalwaysbepresent,thoughit neednot beblack. Any otherpenintherange#1. . .#31maybeomitted.

If HPGL_VERSIONis " 2" thenpic2plot -T hpgl will alsobeaffectedby theenvironmentvariableHPGL_ASSIGN_COLORS. If thevalueof thisvariableis " yes" , thenplot -T hpgl willnotberestrictedto thepalettespecifiedin HPGL_PENS: it will assigncolorsto “logical pens”in therange#1. . .#31,asneeded. Thedefault valueis " no" becauseotherthancolor LaserJetprintersandDesignJetplotters,not many HP-GL/2devicesallow theassignmentof colorsto logical pens.In particular, HP-GL/2penplottersdo not.

pic2plot -T tek , which producesoutput for a Tektronix terminalor emulator, checkstheTERMenvironmentvariable.If thevalueof TERMis astringbeginningwith " xterm" , " nxterm" , or" kterm" , it is takenasa signthatpic2plot is runningin anX Window SystemVT100 terminalemulator: anxterm , nxterm , or kterm . Beforedrawing graphics,pic2plot -T tek willemit anescapesequencethatcausestheterminalemulator’s auxiliary Tektronixwindow, which isnormallyhidden,to popup. After thegraphicsaredrawn, anescapesequencethat returnscontrolto theoriginal VT100window will beemitted.TheTektronixwindow will remainon thescreen.

If thevalueof TERMis astringbeginningwith " kermit" , " ansi.sys" , or " nansi.sys" , it is takenasa sign that pic2plot is running in the VT100 terminal emulatorprovided by the MS-DOSversionof kermit . Beforedrawing graphics,pic2plot -T tek will emit anescapesequencethatswitchestheterminalemulatorto Tektronixmode. Also, someof theTektronixcontrolcodesemittedby pic2plot -T tek will bekermit -specific.Therewill bea limited amountof colorsupport,which is not normally the case(the 16 ansi.sys colors will be supported). Afterdrawing graphics,pic2plot -T tek will emit an escapesequencethat returnsthe emulatortoVT100mode.Thekey sequence‘ALT minus’ canbeemployedmanuallywithin kermit to switchbetweenthetwo modes.

Page 49: plotutils

Chapter5: Thetek2plot Program 44

5 The tek2plot Program

5.1 What tek2plot is usedfor

GNU tek2plot is a command-lineTektronix translator. It displaysTektronixgraphicsfiles,or translatesthemto otherformats.The‘ -T ’ optionis usedto specifytheoutputformator displaytype. Supportedoutputformatsinclude" X" , " png" , " pnm" , " gif" , " svg" , " ai" , " ps" , " cgm" ," fig" , " pcl" , " hpgl" , " regis" , " tek" , and" meta" (thedefault). Thesearethesameformatsthataresupportedby theGNU graph , plot , andpic2plot programs.tek2plot will take inputfrom a file specifiedon thecommandline or from standardinput, justastheplot filter plot does.

Tektronix graphics files are produced by many older applications, such as SKYMAP(http://tdc-www. har va rd .e du/so ft ware /s kymap), a powerful astronomicaldisplayprogram. A directory containingsampleTektronix graphicsfiles, which you may experimentwith, is distributed along with the GNU plotting utilities. On most systemsit is installed as‘ /usr/share/tek2 plo t ’ or ‘ /usr/local/share /t ek 2plo t ’.

Tektronixgraphicsformatisdefinedasanoninteractiveversionof thegraphicsformatunderstoodby Tektronix4010/4014terminals,asdocumentedin the4014ServiceManual, TektronixInc.,1974(TektronixPart #070-1648-00).tek2plot doesnot supportinteractive featuressuchasgraphicsinput mode(“GIN mode”) or statusenquiry. However, it doessupporta few additionalfeaturesprovidedby popularTektronixemulators,suchasthecolor extensionssupportedby theTektronixemulatorcontainedin theMS-DOSversionof kermit .

5.2 tek2plot command-lineoptions

The tek2plot programtranslatestheTektronixgraphicsfiles producedby many olderappli-cationsto otherformats. Theoutputformator displaytype is specifiedwith the ‘ -T ’ option. Thepossibleoutputformatsarethesameformatsthat aresupportedby the GNU graph , plot , andpic2plot programs.

Input file namesmaybespecifiedanywhereon thecommandline. That is, therelative orderoffile namesandcommand-lineoptionsdoesnot matter. If no files arespecified,or thefile name‘ - ’is specified,thestandardinput is read. An outputfile is written to standardoutput,unlessthe ‘ -TX’ optionis specified.In thatcasetheoutputis displayedin oneor morewindows onanX WindowSystemdisplay, andthereis no outputfile.

Thefull setof command-lineoptionsis listedbelow. Therearethreesortsof option:

1. Generaloptions.

2. Optionsrelevantonly to raw tek2plot , i.e.,relevantonly if nodisplaytypeor outputformatis specifiedwith the‘ -T ’ option.

3. Optionsrequestinginformation(e.g.,‘ --help ’).

Eachoptionthattakesanargumentis followed,in parentheses,by thetypeanddefault valueof theargument.

Thefollowing aregeneraloptions.

Page 50: plotutils

Chapter5: Thetek2plot Program 45

‘ -T type’‘ --display-type type’

(String,default " meta" .) Selecta displaytype or outputformat of type type, whichmaybe oneof thestrings" X" , " png" , " pnm" , " gif" , " svg" , " ai" , " ps" , " cgm" ," fig" , " pcl" , " hpgl" , " regis" , " tek" , and" meta" . Theserefer respectively to theX Window System, PNGformat,portableanymap(PBM/PGM/PPM)format,pseudo-GIF format,thenew XML-basedScalableVectorGraphicsformat,theformatusedbyAdobeIllustrator, idraw -editablePostscript,theWebCGMformatfor Web-basedvec-tor graphics,theformatusedby thexfig drawing editor, theHewlett–PackardPCL 5printerlanguage,theHewlett–PackardGraphicsLanguage(by default, HP-GL/2),theReGIS(remotegraphicsinstructionset)formatdevelopedby DEC, Tektronixformat,anddevice-independentGNU graphicsmetafileformat.

‘ -p n’‘ --page-number n’

(Nonnegative integer.) Display only pagenumbern, within the Tektronix file orsequenceof Tektronixfiles thatis beingtranslated.Tektronixfilesmayconsistof oneor morepages,numberedbeginningwith zero.

Thedefaultbehavior, if the‘ -p ’ optionis notused,is to displayall nonemptypagesinsuccession.For example,tek2plot -T X displayseachpagein its own X window.If the ‘ -T png ’ option, the ‘ -T pnm’ option, the ‘ -T gif ’ option, the ‘ -T svg ’option, the‘ -T ai ’ option,or the ‘ -T fig ’ option is used,thedefault behavior is todisplayonly the first page,sincefiles in PNG, PNM, pseudo-GIF, SVG, AI, or Figformatmaycontainonly asinglepageof graphics.

Most Tektronix files consistof either one page(page#0) or two pages(anemptypage#0, andpage#1). Tektronixfilesproducedby theGNU plottingutilities (e.g.,bygraph -T tek ) arenormallyof thelattersort.

‘ -F font name’‘ --font-name font name’

(String, default " Courier" except for tek2plot -T png , tek2plot -T pnm,tek2plot -T gif , tek2plot -T hpgl , tek2plot -T regis , and rawtek2plot , for all of which " HersheySerif" is thedefault.) Setthefont usedfor textto font name. Font namesarecase-insensitive. If a font outsidethe Courier familyis chosen,the ‘ --position-char s ’ option (seebelow) shouldprobablybeused.For a list of all fonts,seeSectionA.1 [Text Fonts],page134. If thespecifiedfont isnotavailable,thedefault font will beused.

If you intendto print a PCL5 file preparedwith tek2plot -T pcl on a LaserJetIII, you shouldspecify a font other than Courier. That is becausethe LaserJetIII,whichwasHewlett–Packard’sfirst PCL 5 printer, did notcomewith ascalableCouriertypeface.Theonly PCL5 fontsit supportedweretheeightfontsin theCGTimesandUniversfamilies.SeeSectionA.1 [Text Fonts],page134.

‘ -W line width’‘ --line-width line width’

(Float,default ? 1.0.) Setthethicknessof lines,asafractionof thesize(i.e.,minimumdimension)of the graphicsdisplay, to line width. A negative value meansthat thedefault valueprovided by theGNU libplot graphicslibrary shouldbeused.This

Page 51: plotutils

Chapter5: Thetek2plot Program 46

is usually1/850timesthesizeof thedisplay, althoughif ‘ -T X’, ‘ -T png ’, ‘ -T pnm’,or ‘ -T gif ’ is specified,it is zero.By convention,azero-thicknessline is thethinnestline thatcanbedrawn. This is thecasein all outputformats.Note,however, that thedrawing editorsidraw andxfig treatzero-thicknesslinesasinvisible.

tek2plot -T regis doesnotsupportdrawing lineswith otherthanadefault thick-ness,andtek2plot -T hpgl doesnotsupportdoingsoif theenvironmentvariableHPGL_VERSIONis setto avaluelessthan" 2" (thedefault).

‘ --bg-color name’(String, default " white" .) Set the color usedfor the backgroundto be name. Thisis relevant only to tek2plot -T X, tek2plot -T png , tek2plot -T pnm,tek2plot -T gif , tek2plot -T cgm, tek2plot -T regis , andtek2plot-T meta . An unrecognizednamesetsthe color to the default. For informationon what namesare recognized,seeAppendix B [Color Names],page155. TheenvironmentvariableBG_COLORcanequallywell beusedto specifythebackgroundcolor.

If the ‘ -T png ’ or ‘ -T gif ’ option is used,a transparentPNG file or a transparentpseudo-GIF, respectively, may be producedby settingthe TRANSPARENT_COLORenvironmentvariableto thenameof thebackgroundcolor. SeeSection5.3 [tek2plotEnvironment],page49. If the ‘ -T svg ’ or ‘ -T cgm’ option is used,an outputfilewithout abackgroundmaybeproducedby settingthebackgroundcolor to " none" .

‘ --bitmap-size bitmapsize’(String,default " 570x570" .) Setthesizeof thegraphicsdisplayin whichtheplot willbe drawn, in termsof pixels, to be bitmapsize. This is relevant only to tek2plot-T X, tek2plot -T png , tek2plot -T pnm, and tek2plot -T gif , for allof which the size can be expressedin terms of pixels. The environment variableBITMAPSIZE mayequallywell beusedto specifythesize.

Thegraphicsdisplayusedby tek2plot -T X is apopped-upX window. Command-line positioningof this window on an X Window Systemdisplay is supported.Forexample,if bitmap sizeis " 570x570+0+0" thenthewindow will bepoppedup in theupperleft corner.

If youchoosearectangular(non-square)window size,thefontsin theplotwill bescaledanisotropically, i.e.,bydifferentfactorsin thehorizontalandverticaldirection.Forthis,tek2plot -T X requiresanX11R6display. Any font thatcannotbeanisotropicallyscaledwill be replacedby a default scalablefont, suchas the Hershey vector font" HersheySerif" .

For backward compatibility, tek2plot -T X allows the user to set the windowsize and position by setting the X resource Xplot.geometry , instead of‘ --bitmap-size ’ or BITMAPSIZE .

‘ --emulate-color option’(String, default " no" .) If option is " yes" , replaceeachcolor in the output by anappropriateshadeof gray. This is seldomuseful, except when using ‘ tek2plot-T pcl ’ to prepareoutputfor a PCL5 device. (Many monochromePCL5 devices,suchasmonochromeLaserJets,do a poor job of emulatingcolor on their own. TheyusuallymapHP-GL/2’s seven standardpencolors,including even yellow, to black.)

Page 52: plotutils

Chapter5: Thetek2plot Program 47

You may equally well requestcolor emulationby settingthe environmentvariableEMULATE_COLORto " yes" .

‘ --max-line-leng th max line length’(Integer, default 500.) Setthemaximumnumberof pointsthata polygonalline maycontain,beforeit is flushedto the output device, to equalmax line length. If thisflushingoccurs,thepolygonalline will besplit into two or moresub-lines,thoughthesplitting shouldnotbenoticeable.

The reasonfor splitting long polygonallines is that somedisplaydevices (e.g.,oldPostscriptprintersandHP-GLpenplotters)havelimitedbuffer sizes.TheenvironmentvariableMAX_LINE_LENGTHcanalsobeusedto specifythemaximumline length.Thisoptionhasnoeffecton raw tek2plot , sinceit draws polylinesin realtimeandhasno buffer limitations.

‘ --page-size pagesize’(String,default " letter" .) Setthesizeof thepageonwhichtheplot will bepositioned.This is relevantonly to tek2plot -T svg , tek2plot -T ai , tek2plot -T ps ,tek2plot -T cgm, tek2plot -T fig , tek2plot -T pcl , andtek2plot -Thpgl . " letter" meansan 8.5in by 11in page. Any ISO pagesize in the range" a0" . . . " a4" or ANSI pagesizein therange" a" . . . " e" maybespecified(" letter"is analiasfor " a" and" tabloid" is analiasfor " b" ). " legal" , " ledger" , and" b5" arerecognizedpagesizesalso.TheenvironmentvariablePAGESIZEcanequallywell beusedto specifythepagesize.

For tek2plot -T ai , tek2plot -T ps , tek2plot -T pcl , andtek2plot -T fig , thegraphicsdisplay(or ‘viewport’) within which theplot is drawn will be,bydefault, a squareregion centeredon thespecifiedpage.For tek2plot -T hpgl , itwill bea squareregion of thesamesize,but maybepositioneddifferently. Eitherorbothof thedimensionsof thegraphicsdisplaycanbespecifiedexplicitly. For example,pagesizecould be specifiedas" letter,xsize=4in" , or " a4,xsize=10cm,ysize=15cm" .Thedimensionsareallowedtobenegative(anegativedimensionresultsin areflection).

The positionof the graphicsdisplay, relative to its default position,may optionallybeadjustedby specifyinganoffset vector. For example,pagesizecouldbespecifiedas " letter,yoffset=1.2in" , or " a4,xoffset=@ 5mm,yoffset=2.0cm" . It is alsopossibleto positionthe graphicsdisplayprecisely, by specifyingthe locationof its lower leftcornerrelative to the lower left cornerof the page. For example,pagesizecould bespecifiedas" letter,xorigin=2in,yorigin=3in" , or " a4,xorigin=0.5cm,yorigin=0.5cm" .Theprecedingoptionsmaybeintermingled.tek2plot -T svg andtek2plot -Tcgm ignorethe " xoffset" , " yoffset" , " xorigin" , and" yorigin" options,sinceSVGformatandWebCGMformathave no notionof theWebpageon which thegraphicsdisplaywill ultimatelybepositioned.For moreon pagesizes,seeAppendixC [PageandViewportSizes],page156.

‘ --pen-color name’(String,default " black" .) Setthepencolor to bename. An unrecognizednamesetsthepencolor to thedefault. For informationon whatcolor namesarerecognized,seeAppendixB [Color Names],page155.

Page 53: plotutils

Chapter5: Thetek2plot Program 48

‘ --position-char s ’Positionthecharactersin eachtext stringindividually on thedisplay. If thetext font isnot a memberof theCourierfamily, andespeciallyif it is not a fixed-widthfont, thisoptionis recommended.It will improve theappearanceof text strings,at thepriceofmakingit difficult to edit theoutputfile with xfig or idraw .

‘ --rotation angle’(Integer, default 0.) Settherotationangleof thegraphicsdisplayto beangledegrees.Recognizedvaluesare0, 90, 180, and270. The rotation is counterclockwise.Theenvironment variableROTATIONcan equally well be usedto specify the rotationangle.

This option is usedfor switchingbetweenportrait andlandscapeorientations.Post-modernistsmayalsofind it useful.

‘ --use-tek-fonts ’Use the bitmap fonts that were usedon the original Tektronix 4010/4014terminal.This option is relevant only to tek2plot -T X. The four relevant bitmap fontsaredistributedwith mostversionsof the plotting utilities package,underthe namestekfont0 . . . tekfont3 . They mayeasilybeinstalledon any modernX WindowSystemdisplay. For thisoptionto work properly, youmustalsoselectawindow sizeof1024x1024pixels,eitherby usingthe‘ --bitmap-size 1024x1024 ’ optionor bysettingthevalueof theXplot.geometry resource.Thereasonfor this restrictionis that bitmapfonts, unlike the scalablefonts that the plotting utilities normally use,cannotberescaled.

This option is usefulonly if you have a file in Tektronixformat thatdraws text usingnativeTektronixfonts. Tektronixfilesproducedby theGNU plottingutilities (e.g.,bygraph -T tek ) do notusenative Tektronixfontsto draw text.

Thefollowing optionis relevantonly to raw tek2plot , i.e., relevantonly if nodisplaytypeoroutputformatis specifiedwith the‘ -T ’ option. In thiscasetek2plot outputsagraphicsmetafile,whichmaybetranslatedto otherformatsby invoking plot .

‘ -O ’‘ --portable-outp ut ’

Outputtheportable(human-readable)versionof GNU metafileformat, ratherthanabinary version(the default). This canalsobe requestedby settingthe environmentvariableMETA_PORTABLEto " yes" .

Thefollowing optionsrequestinformation.

‘ --help ’ Print a list of command-lineoptions,andthenexit.

‘ --help-fonts ’Print a table of available fonts, and then exit. The table will dependon whichdisplay type or output format is specifiedwith the ‘ -T ’ option. tek2plot -T X,tek2plot -T svg , tek2plot -T ai , tek2plot -T ps , tek2plot -T cgm,and tek2plot -T fig eachsupportthe 35 standardPostscriptfonts. tek2plot-T svg , tek2plot -T ai , tek2plot -T pcl , and tek2plot -T hpgl sup-port the45standardPCL 5 fonts,andtek2plot -T pcl andtek2plot -T hpglsupporta numberof Hewlett–Packardvector fonts. All of the preceding,together

Page 54: plotutils

Chapter5: Thetek2plot Program 49

with tek2plot -T png , tek2plot -T pnm, tek2plot -T gif , tek2plot -T regis , and tek2plot -T tek , supporta setof 22 Hershey vector fonts. Rawtek2plot in principlesupportsany of thesefonts,sinceits outputmustbetranslatedto otherformatswith plot . Theplotfont utility will producea charactermapofany availablefont. SeeChapter6 [plotfont], page51.

‘ --list-fonts ’Like ‘ --help-fonts ’, but lists the fonts in a singlecolumnto facilitatepiping tootherprograms.If no displaytypeor outputformat is specifiedwith the‘ -T ’ option,thefull setof supportedfontsis listed.

‘ --version ’Print theversionnumberof tek2plot andtheplotting utilities package,andexit.

5.3 Environmentvariables

Thebehavior of tek2plot is affectedby severalenvironmentvariables,whicharethesameasthosethataffectgraph andplot . For convenience,we list themhere.

WehavealreadymentionedtheenvironmentvariablesBITMAPSIZE ,PAGESIZE, BG_COLOR,EMULATE_COLOR, MAX_LINE_LENGTH, andROTATION. They serve asbackupsfor the sev-eral options ‘ --bitmap-size ’, ‘ --page-size ’, ‘ --bg-color ’, ‘ --emulate-colo r ’,‘ --max-line-leng th ’, and ‘ --rotation ’. The remainingenvironmentvariablesarespe-cific to individual outputformats.

tek2plot -T X, whichpopsupawindow onanX Window Systemdisplayanddrawsgraphicsin it, checkstheDISPLAY environmentvariable.Thevalueof this variabledeterminesthedisplayon which thewindow will bepoppedup.

tek2plot -T png andtek2plot -T gif , whichproduceoutputin PNGformatandpseudo-GIF formatrespectively, areaffectedby two environmentvariables.If thevalueof theINTERLACEvariableis " yes" , the outputfile will be interlaced. Also, if the value of the TRANSPARENT_COLORenvironmentvariableis thenameof acolor thatappearsin theoutputfile, thatcolorwill betreatedastransparentby mostapplications.For informationon whatcolor namesarerecognized,seeAppendixB [Color Names],page155.

tek2plot -T pnm, which producesoutputin PortableAnymap(PBM/PGM/PPM)format,isaffectedby the PNM_PORTABLEenvironmentvariable. If its valueis " yes" , the outputfile willbein theportable(humanreadable)versionof PBM, PGM,or PPMformat,ratherthanthedefault(binary)version.

tek2plot -T cgm, whichproducesCGMfilesthatcomplywith theWebCGMprofilefor Web-basedvectorgraphics,is affectedby two environmentvariables.By default,aversion3 CGM file isgenerated.Many olderCGM interpretersandviewers,suchastheonesbuilt into Microsoft Officeand other commercialsoftware, only supportversion1 CGM files. The CGM_MAX_VERSIONenvironmentvariablemay be set to " 1" , " 2" , " 3" , or " 4" (the default) to specifya maximumvaluefor theversionnumber. TheCGM_ENCODINGvariablemayalsobeset,to specifythe typeof encodingusedin the CGM file. Supportedvaluesare" clear text" (i.e., humanreadable)and" binary" (thedefault). TheWebCGMprofile requiresthatthebinaryencodingbeused.

tek2plot -T pcl , which producesPCL 5 output for Hewlett–Packardprinters,is affectedby theenvironmentvariablePCL_ASSIGN_COLORS. It shouldbesetto " yes" whenproducing

Page 55: plotutils

Chapter5: Thetek2plot Program 50

PCL5 outputfor a colorprinteror othercolor device. This will ensureaccuratecolor reproductionby giving theoutputdevice completefreedomin assigningcolors,internally, to its “logical pens”.If it is " no" thenthedevice will usea fixedsetof coloredpens,andwill emulateothercolorsbyshading.Thedefault is " no" becausemonochromePCL 5 devices,which aremorecommonthancoloredones,mustuseshadingto emulatecolor.

tek2plot -T hpgl , which producesHewlett–PackardGraphicsLanguageoutput, is alsoaffectedby several environmentvariables. The most importantis HPGL_VERSION, which maybe setto " 1" , " 1.5" , or " 2" (thedefault). " 1" meansthat theoutputshouldbe genericHP-GL," 1.5" meansthat theoutputshouldbesuitablefor theHP7550AgraphicsplotterandtheHP758x,HP7595AandHP7596Adraftingplotters(HP-GLwith someHP-GL/2extensions),and" 2" meansthat theoutputshouldbemodernHP-GL/2. If theversionis " 1" or " 1.5" thentheonly availablefontswill bevectorfonts,andall lineswill bedrawn with a default thickness(the‘ -W’ optionwillnotwork).

Thepositionof thetek2plot -T hpgl graphicsdisplayonthepagecanberotated90 degreescounterclockwiseby settingthe HPGL_ROTATEenvironmentvariableto " yes" . This is not thesameasthe rotationobtainedwith the ‘ --rotation ’ option, sinceit both rotatesthe graphicsdisplayandrepositionsits lower left cornertowardanothercornerof thepage.Besides" no" and" yes" , recognizedvaluesfor the HPGL_ROTATEvariableare " 0" , " 90" , " 180" , and" 270" ." no" and" yes" areequivalent to " 0" and" 90" , respectively. " 180" and" 270" aresupportedonly if HPGL_VERSIONis " 2" (thedefault).

Thedrawing of visiblewhitelinesis supportedonly if HPGL_VERSIONis " 2" andtheenviron-mentvariableHPGL_OPAQUE_MODE is " yes" (thedefault). If thevalueis " no" thenwhite lines(if any), whicharenormallydrawn with pen#0, will notbedrawn. This featureis to accommodateolder HP-GL/2 devices. HP-GL/2 penplotters,for example, do not supportthe useof pen#0 todraw visible white lines. SomeolderHP-GL/2devicesmay, in fact, malfunctionif asked to drawopaqueobjects.

By default, tek2plot -T hpgl will draw with a fixed setof pens. Which pensarepresentmaybespecifiedby settingtheHPGL_PENSenvironmentvariable.If HPGL_VERSIONis " 1" , thedefault valueof HPGL_PENSis " 1=black" ; if HPGL_VERSIONis " 1.5" or " 2" , thedefault valueof HPGL_PENSis " 1=black:2=red:3=green:4=yellow:5=blue:6=magenta:7=cyan" . The formatshouldbe self-explanatory. By settingHPGL_PENS, you may specifya color for any penin therange#1. . .#31. For informationon what color namesare recognized,seeAppendix B [ColorNames],page155. Pen#1 mustalwaysbepresent,thoughit neednot beblack. Any otherpenintherange#1. . .#31maybeomitted.

If HPGL_VERSIONis " 2" thentek2plot -T hpgl will alsobeaffectedby theenvironmentvariableHPGL_ASSIGN_COLORS. If the value of this variableis " yes" , then tek2plot -Thpgl will notberestrictedto thepalettespecifiedin HPGL_PENS: it will assigncolorsto “logicalpens”in therange#1. . .#31,asneeded. Thedefaultvalueis " no" becauseotherthancolorLaserJetprintersandDesignJetplotters,notmany HP-GL/2devicesallow theassignmentof colorsto logicalpens.In particular, HP-GL/2penplottersdo not.

Page 56: plotutils

Chapter6: Theplotfont Utility 51

6 The plotfont Utility

6.1 How to useplotfont

GNU plotfont is a simpleutility thatwill producea charactermapfor any font availabletotheGNU plotting utilities graph , plot , pic2plot , andtek2plot , andtheGNU libplotgraphicslibrary on which they arebased. The mapmay be displayedon an X Window Systemdisplay, or producedin any of severaloutputformats.The‘ -T ’ optionis usedto specifythedesiredoutputformat. Supportedoutputformatsinclude" X" , " png" , " pnm" , " gif" , " svg" , " ai" , " ps" ," cgm" , " fig" , " pcl" , " hpgl" , " regis" , " tek" , and" meta" (thedefault).

Which fontsareavailabledependson thechoiceof displayor outputformat. To geta list of theavailablefonts,usethe‘ --help-fonts ’ option. For example,

plotfont -T ps --help-fonts

will list thefontsthatareavailablewhenproducingPostscriptoutput.Oneof thesefontsis " Times-Roman" . Doing

plotfont -T ps Times-Roman > map.ps

will producea charactermap of the lower half of this font, which consistsof printableASCIIcharacters.Themapwill bea 12x8grid, with a charactercenteredin eachgrid cell. If you includethe‘ -2 ’ option,youwill getamapof theupperhalf of thefont.

Mostbuilt-in fontsareISO-Latin-1fonts,whichmeansthattheupperhalf is arrangedaccordingto theISO-Latin-1encoding.The" HersheyCyrillic" font is onethatis not. If you do

plotfont -T ps -2 HersheyCyrilli c > map.ps

youwill getamapthatillustratesits arrangment,whichis calledKOI8-R. TheKOI8-Rarrangementis thestandardfor Unix andnetworkingapplicationsin theformerSoviet Union. So-calleddingbatsfonts, suchas " ZapfDingbats" and " Wingdings" , also have an individualistic layout. In mostinstallationsof theplotting utilities, theWingdingsfont is not availablewhenproducingPostscriptoutput.However, it is availablewhenproducingoutputin PCL5 or HP-GL/2format. If youdo

plotfont -T hpgl Wingdings > map.plt

youwill getaWingdingscharactermap,in HP-GL/2format,thatmaybeimportedinto any applica-tion thatunderstandsHP-GL/2. Similarly, plot -T pcl Wingdings will producea Wingdingscharactermapin PCL5 format,whichmaybeprintedon aLaserJetor otherPCL 5 device.

In all, morethanahundredfontsarebuilt into theplottingutilities. SeeSectionA.1 [Text Fonts],page134. Actually, if you areusingtheplotting utilities to displayoutputon anX display, you arenot restrictedto thebuilt-in fonts. Doing

plotfont -T X --help-fonts

producesa list of thebuilt-in fonts thatareavailable,includingbothHershey andPostscriptfonts.But fonts availableon your X displaymay alsobe used. The xlsfonts commandwill list thefontsavailableonyourX display, mostfont namesbeinggivenin whatis calledXLFD format. Theplottingutilities referto X fontsby shortenedversionsof theirXLFD names.For example,thefont" Utopia-Regular" is availableon many X displays. Its XLFD nameis " -adobe-utopia-medium-r-normal–0-0-0-0-p-0-iso8859-1" , andits shortenedXLFD nameis " utopia-medium-r-normal" . Ifyoudo

Page 57: plotutils

Chapter6: Theplotfont Utility 52

plotfont -T X utopia-medium- r- normal

thenacharactermapfor this font will bedisplayedin apopped-upX window.

When using the ‘ -T X’ option, you may also usethe ‘ --bitmap-size ’ option to choosethesizeof thepopped-upwindow. ModernX displayscanscalefontsby differentamountsin thehorizontalandverticaldirections. If, for example,you add‘ --bitmap-size 600x300 ’ to theabovecommandline, boththecharactermapandtheUtopia-Regularfont within it will bescaledinthisway. If yourX displaydoesnot supportfont scaling,ascalablefont will besubstituted.

6.2 plotfont command-lineoptions

Theplotfont font displayutility will producea charactermapfor any of thefontsavailableto theGNU plottingutilities graph , plot , pic2plot , andtek2plot , andtheGNU libplotgraphicslibrary onwhichthey arebased.Themapmaybeproducedin any supportedoutputformat,or displayedon anX Window Systemdisplay. Theoutputformator displaytypeis specifiedwiththe‘ -T ’ option.

Thenamesof thefontsfor whichacharactermapwill beproducedmayappearanywhereontheplotfont commandline. Thatis, therelativeorderof font namesandcommand-lineoptionsdoesnot matter. Thecharactermapis written to standardoutput,unlessthe ‘ -T X’ option is specified.In thatcasethecharactermapis displayedin awindow onanX Window Systemdisplay, andthereis no outputfile.

Thepossibleoptionsarelistedbelow. Therearethreesortsof option:

1. Generaloptions.

2. Optionsrelevantonly to raw plotfont , i.e.,relevantonly if nodisplaytypeor outputformatis specifiedwith the‘ -T ’ option.

3. Optionsrequestinginformation(e.g.,‘ --help ’).

Eachoptionthattakesanargumentis followed,in parentheses,by thetypeanddefault valueof theargument.

Thefollowing aregeneraloptions.

‘ -1 ’‘ --lower-half ’

Generateacharactermapfor thelowerhalf of eachspecifiedfont. This is thedefault.

‘ -2 ’‘ --upper-half ’

Generateacharactermapfor theupperhalf of eachspecifiedfont.

‘ -o ’‘ --octal ’

Numberthecharactersin octalratherthanin decimal(thedefault).

‘ -x ’‘ --hexadecimal ’

Numberthecharactersin hexadecimalratherthanin decimal(thedefault).

‘ --box ’ Surroundeachcharacterwith abox,showing its extentto left andright. Thedefault isnot to do this.

Page 58: plotutils

Chapter6: Theplotfont Utility 53

‘ -j row’‘ --jis-row row’

Generatea charactermapfor row row of a Japanesefont arrangedaccordingto JIS[JapaneseIndustrialStandard]X0208. The only suchfont currentlyavailable is theHersheyEUC [ExtendedUnix Code]font. If used, this optionoverridesthe ‘ -1 ’ and‘ -2 ’ options.

Thevalid rowsare1. . .94. In theJISX0208standard,Romancharactersarelocatedinrow 3, andJapanesesyllabiccharacters(HiraganaandKatakana)arelocatedin rows4and5. GreekandCyrillic charactersarelocatedin rows6 and7. Japaneseideographiccharacters(Kanji) arelocatedin rows16. . .84. Rows16. . .47containtheJISLevel 1Kanji, which arethe most frequentlyused. They arearrangedaccordingto On (oldChinese)reading.Rows 48. . .84 containthelessfrequentlyusedJISLevel 2 Kanji.

TheHersheyEUCfontcontains596of the2965Level 1 Kanji, andsevenof theLevel 2Kanji. It usesthe8-bit EUC-JPencoding.This encodingis a multibyteencodingthatincludesthe ASCII charactersetaswell as the JIS X0208 characters.It representseachASCII characterin theusualway, i.e.,asasinglebytethatdoesnothave its highbit set. EachJISX0208characteris representedastwo bytes,eachwith thehigh bitset.Thefirst bytecontainstherow number(plus32), andthesecondbytecontainsthecharacternumber.

‘ -T type’‘ --display-type type’

(String,default " meta" .) Selecta displaytype or outputformat of type type, whichmaybe oneof thestrings" X" , " png" , " pnm" , " gif" , " svg" , " ai" , " ps" , " cgm" ," fig" , " pcl" , " hpgl" , " regis" , " tek" , and" meta" . Theserefer respectively to theX Window System, PNGformat,portableanymap(PBM/PGM/PPM)format,pseudo-GIF format,thenew XML-basedScalableVectorGraphicsformat,theformatusedbyAdobeIllustrator, idraw -editablePostscript,theWebCGMformatfor Web-basedvec-tor graphics,theformatusedby thexfig drawing editor, theHewlett–PackardPCL 5printerlanguage,theHewlett–PackardGraphicsLanguage(by default, HP-GL/2),theReGIS(remotegraphicsinstructionset)formatdevelopedby DEC, Tektronixformat,anddevice-independentGNU graphicsmetafileformat.

Files in PNG,PNM, pseudo-GIF, SVG, AI, or Fig formatmay containonly a singlepageof graphics.Soif the‘ -T png ’ option,the‘ -T pnm’ option,the‘ -T gif ’ option,the‘ -T svg ’ option,the‘ -T ai ’ option,or the ‘ -T fig ’ option is used,a charactermapwill beproducedfor only thefirst-specifiedfont.

‘ --bg-color name’(String, default " white" .) Set the color usedfor the backgroundto be name. Thisis relevant only to plotfont -T X, plotfont -T png , plotfont -T pnm,plotfont -T gif , plotfont -T cgm, plotfont -T regis , andplotfont-T meta . An unrecognizednamesetsthe color to the default. For informationon what namesare recognized,seeAppendix B [Color Names],page155. TheenvironmentvariableBG_COLORcanequallywell beusedto specifythebackgroundcolor.

If the ‘ -T png ’ or ‘ -T gif ’ option is used,a transparentPNG file or a transparentpseudo-GIF, respectively, may be producedby settingthe TRANSPARENT_COLOR

Page 59: plotutils

Chapter6: Theplotfont Utility 54

environmentvariableto thenameof thebackgroundcolor. SeeSection6.3 [plotfontEnvironment],page56. If the ‘ -T svg ’ or ‘ -T cgm’ option is used,an outputfilewithout abackgroundmaybeproducedby settingthebackgroundcolor to " none" .

‘ --bitmap-size bitmapsize’(String,default" 570x570" .) Setthesizeof thegraphicsdisplayin whichthecharactermap will be drawn, in terms of pixels, to be bitmap size. This is relevant onlyto plotfont -T X, plotfont -T png , plotfont -T pnm, andplotfont -Tgif , for all of which thesizecanbeexpressedin termsof pixels. TheenvironmentvariableBITMAPSIZE mayequallywell beusedto specifythesize.

Thegraphicsdisplayusedby plotfont -T X is apopped-upX window. Command-line positioningof this window on an X Window Systemdisplay is supported.Forexample,if bitmap sizeis " 570x570+0+0" thenthewindow will bepoppedup in theupperleft corner.

If youchoosearectangular(non-square)window size,thefontsin theplotwill bescaledanisotropically, i.e.,bydifferentfactorsin thehorizontalandverticaldirection.Forthis,plotfont -T X requiresanX11R6display. Any font thatcannotbeanisotropicallyscaledwill be replacedby a default scalablefont, suchas the Hershey vector font" HersheySerif" .

For backward compatibility, plotfont -T X allows the user to set the windowsize and position by setting the X resource Xplot.geometry , instead of‘ --bitmap-size ’ or BITMAPSIZE .

‘ --emulate-color option’(String, default " no" .) If option is " yes" , replaceeachcolor in the output by anappropriateshadeof gray. This is seldomuseful, except when using ‘plotfont-T pcl ’ to prepareoutputfor a PCL5 device. (Many monochromePCL5 devices,suchasmonochromeLaserJets,do a poor job of emulatingcolor on their own. TheyusuallymapHP-GL/2’s seven standardpencolors,including even yellow, to black.)You may equally well requestcolor emulationby settingthe environmentvariableEMULATE_COLORto " yes" .

‘ --numbering-fon t-n ame font name’(String, default " Helvetica" except for plotfont -T pcl , for which " Univers"is the default, and plotfont -T png , plotfont -T pnm, plotfont -T gif ,plotfont -T hpgl , plotfont -T regis , and plotfont -T tek , for all ofwhich " HersheySerif" is the default.) Set the font usedfor the numberingof thecharactersin thecharactermap(s)to befont name.

‘ --page-size pagesize’(String, default " letter" .) Set the size of the pageon which the charactermap(s)will be drawn. This is relevant only to plotfont -T svg , plotfont -T ai ,plotfont -T ps , plotfont -T fig , plotfont -T pcl , and plotfont -Thpgl . " letter" meansan 8.5in by 11in page. Any ISO pagesize in the range" a0" . . . " a4" or ANSI pagesizein therange" a" . . . " e" maybespecified(" letter"is analiasfor " a" and" tabloid" is analiasfor " b" ). " legal" , " ledger" , and" b5" arerecognizedpagesizesalso.TheenvironmentvariablePAGESIZEcanequallywell beusedto specifythepagesize.

Page 60: plotutils

Chapter6: Theplotfont Utility 55

For plotfont -T ai , plotfont -T ps , plotfont -T pcl , andplotfont -T fig , thegraphicsdisplay(or ‘viewport’) within which thecharactermapis drawnwill be,by default, a squareregion centeredon the specifiedpage. For plotfont-T hpgl , it will be a squareregion of the samesize, but may be positioneddif-ferently. Either or both of the dimensionsof the graphicsdisplay can be speci-fied explicitly. For example,pagesizecould be specifiedas " letter,xsize=4in" , or" a4,xsize=10cm,ysize=15cm" . Thedimensionsareallowedto benegative(anegativedimensionresultsin a reflection).

The positionof the graphicsdisplay, relative to its default position,may optionallybeadjustedby specifyinganoffset vector. For example,pagesizecouldbespecifiedas " letter,yoffset=1.2in" , or " a4,xoffset=A 5mm,yoffset=2.0cm" . It is alsopossibleto positionthe graphicsdisplayprecisely, by specifyingthe locationof its lower leftcornerrelative to the lower left cornerof the page. For example,pagesizecould bespecifiedas" letter,xorigin=2in,yorigin=3in" , or " a4,xorigin=0.5cm,yorigin=0.5cm" .Theprecedingoptionsmaybeintermingled.plotfont -T svg andplotfont -Tcgm ignorethe " xoffset" , " yoffset" , " xorigin" , and" yorigin" options,sinceSVGformatandWebCGMformathave no notionof theWebpageon which thegraphicsdisplaywill ultimatelybepositioned.For moreon pagesizes,seeAppendixC [PageandViewportSizes],page156.

‘ --pen-color name’(String,default " black" .) Setthepencolor to bename. An unrecognizednamesetsthepencolor to thedefault. For informationon whatcolor namesarerecognized,seeAppendixB [Color Names],page155.

‘ --rotation angle’(Integer, default 0.) Settherotationangleof thegraphicsdisplayto beangledegrees.Recognizedvaluesare0, 90, 180, and270. The rotation is counterclockwise.Theenvironment variableROTATIONcan equally well be usedto specify the rotationangle.

This option is usedfor switchingbetweenportrait andlandscapeorientations.Post-modernistsmayalsofind it useful.

‘ --title-font-na mefont name’(String) Set the font usedfor the title of eachcharactermapto be font name. Nor-mally the font usedfor the title is the sameasthe font whosecharacterset is beingdisplayed.Thisoptionis usefulwhenproducingcharactermapsfor unusualfontssuchas" ZapfDingbats" and" Wingdings" .

Thefollowing optionis relevantonly to raw plotfont , i.e., relevantonly if nodisplaytypeoroutputformatis specifiedwith the‘ -T ’ option. In thiscaseplotfont outputsagraphicsmetafile,whichmaybetranslatedto otherformatsby invoking plot .

‘ -O ’‘ --portable-outp ut ’

Outputtheportable(human-readable)versionof GNU metafileformat, ratherthanabinary version(the default). This canalsobe requestedby settingthe environmentvariableMETA_PORTABLEto " yes" .

Thefollowing optionsrequestinformation.

Page 61: plotutils

Chapter6: Theplotfont Utility 56

‘ --help ’ Print a list of command-lineoptions,andthenexit.

‘ --help-fonts ’Print a table of available fonts, and then exit. The table will dependon whichdisplay type or output format is specifiedwith the ‘ -T ’ option. plotfont -T X,plotfont -T svg , plotfont -T ai , plotfont -T ps , plotfont -T cgm,andplotfont -T fig eachsupportthe 35 standardPostscriptfonts. plotfont-T svg , plotfont -T ai , plotfont -T pcl , and plotfont -T hpgl sup-port the45standardPCL 5 fonts,andplotfont -T pcl andplotfont -T hpglsupporta numberof Hewlett–Packardvector fonts. All of the preceding,togetherwith plotfont -T png , plotfont -T pnm, plotfont -T gif , plotfont -T regis , andplotfont -T tek , supporta setof 22 Hershey vector fonts. Rawplotfont in principlesupportsany of thesefonts,sinceits outputmustbetranslatedto otherformatswith plot .

‘ --list-fonts ’Like ‘ --help-fonts ’, but lists the fonts in a singlecolumnto facilitatepiping tootherprograms.If no displaytypeor outputformat is specifiedwith the‘ -T ’ option,thefull setof supportedfontsis listed.

‘ --version ’Print theversionnumberof plotfont andtheplotting utilities package,andexit.

6.3 Environmentvariables

Thebehavior of plotfont is affectedby severalenvironmentvariables,whicharethesameasthosethataffectgraph , plot , andtek2plot . For convenience,we list themhere.

We have already mentioned the environment variables BITMAPSIZE , PAGESIZE,BG_COLOR, ‘EMULATE_COLOR’, and ROTATION. They serve as backupsfor the severaloptions ‘ --bitmap-size ’, ‘ --page-size ’, ‘ --bg-color ’, --emulate-color , and‘ --rotation ’. Theremainingenvironmentvariablesarespecificto individual outputformats.

plotfont -T X, which pops up a window on an X Window Systemdisplay and draws acharactermapin it, checkstheDISPLAY environmentvariable. Thevalueof thisvariabledeterminesthedisplayon which thewindow will bepoppedup.

plotfont -T png andplotfont -T gif , whichproduceoutputin PNGformatandpseudo-GIF formatrespectively, areaffectedby two environmentvariables.If thevalueof theINTERLACEvariableis " yes" , the outputfile will be interlaced. Also, if the value of the TRANSPARENT_COLORenvironmentvariableis thenameof acolor thatappearsin theoutputfile, thatcolorwill betreatedastransparentby mostapplications.For informationon whatcolor namesarerecognized,seeAppendixB [Color Names],page155.

plotfont -T pnm, which producesoutputin PortableAnymap(PBM/PGM/PPM)format,isaffectedby the PNM_PORTABLEenvironmentvariable. If its valueis " yes" , the outputfile willbein theportable(humanreadable)versionof PBM, PGM,or PPMformat,ratherthanthedefault(binary)version.

plotfont -T cgm, whichproducesCGMfilesthatcomplywith theWebCGMprofilefor Web-basedvectorgraphics,is affectedby two environmentvariables.By default,aversion3 CGM file isgenerated.Many olderCGM interpretersandviewers,suchastheonesbuilt into Microsoft Office

Page 62: plotutils

Chapter6: Theplotfont Utility 57

and other commercialsoftware, only supportversion1 CGM files. The CGM_MAX_VERSIONenvironmentvariablemay be set to " 1" , " 2" , " 3" , or " 4" (the default) to specifya maximumvaluefor theversionnumber. TheCGM_ENCODINGvariablemayalsobeset,to specifythe typeof encodingusedin the CGM file. Supportedvaluesare" clear text" (i.e., humanreadable)and" binary" (thedefault). TheWebCGMprofile requiresthatthebinaryencodingbeused.

plotfont -T pcl , which producesPCL 5 output for Hewlett–Packardprinters,is affectedby theenvironmentvariablePCL_ASSIGN_COLORS. It shouldbesetto " yes" whenproducingPCL5 outputfor a colorprinteror othercolor device. This will ensureaccuratecolor reproductionby giving theoutputdevice completefreedomin assigningcolors,internally, to its “logical pens”.If it is " no" thenthedevice will usea fixedsetof coloredpens,andwill emulateothercolorsbyshading.Thedefault is " no" becausemonochromePCL 5 devices,which aremorecommonthancoloredones,mustuseshadingto emulatecolor.

plotfont -T hpgl , which producesHewlett–PackardGraphicsLanguageoutput, is alsoaffectedby several environmentvariables. The most importantis HPGL_VERSION, which maybe setto " 1" , " 1.5" , or " 2" (thedefault). " 1" meansthat theoutputshouldbe genericHP-GL," 1.5" meansthat theoutputshouldbesuitablefor theHP7550AgraphicsplotterandtheHP758x,HP7595AandHP7596Adraftingplotters(HP-GLwith someHP-GL/2extensions),and" 2" meansthat theoutputshouldbemodernHP-GL/2. If theversionis " 1" or " 1.5" thentheonly availablefontswill bevectorfonts.

Thepositionof theplotfont -T hpgl graphicsdisplayonthepagecanberotated90 degreescounterclockwiseby settingthe HPGL_ROTATEenvironmentvariableto " yes" . This is not thesameasthe rotationobtainedwith the ‘ --rotation ’ option, sinceit both rotatesthe graphicsdisplayandrepositionsits lower left cornertowardanothercornerof thepage.Besides" no" and" yes" , recognizedvaluesfor the HPGL_ROTATEvariableare " 0" , " 90" , " 180" , and" 270" ." no" and" yes" areequivalent to " 0" and" 90" , respectively. " 180" and" 270" aresupportedonly if HPGL_VERSIONis " 2" (thedefault).

By default, plotfont -T hpgl will draw with a fixed setof pens. Which pensarepresentmaybespecifiedby settingtheHPGL_PENSenvironmentvariable.If HPGL_VERSIONis " 1" , thedefault valueof HPGL_PENSis " 1=black" ; if HPGL_VERSIONis " 1.5" or " 2" , thedefault valueof HPGL_PENSis " 1=black:2=red:3=green:4=yellow:5=blue:6=magenta:7=cyan" . The formatshouldbe self-explanatory. By settingHPGL_PENS, you may specifya color for any penin therange#1. . .#31. For informationon what color namesare recognized,seeAppendix B [ColorNames],page155. Pen#1 mustalwaysbepresent,thoughit neednot beblack. Any otherpenintherange#1. . .#31maybeomitted.

If HPGL_VERSIONis " 2" thenplotfont -T hpgl will alsobeaffectedby theenvironmentvariableHPGL_ASSIGN_COLORS. If the value of this variableis " yes" , then plotfont -Thpgl will notberestrictedto thepalettespecifiedin HPGL_PENS: it will assigncolorsto “logicalpens”in therange#1. . .#31,asneeded. Thedefaultvalueis " no" becauseotherthancolorLaserJetprintersandDesignJetplotters,notmany HP-GL/2devicesallow theassignmentof colorsto logicalpens.In particular, HP-GL/2penplottersdo not.

plotfont -T tek , which producesoutput for a Tektronix terminalor emulator, checkstheTERMenvironmentvariable.If thevalueof TERMis astringbeginningwith " xterm" , " nxterm" , or" kterm" , it is takenasa signthatplotfont is runningin anX Window SystemVT100 terminalemulator: anxterm , nxterm , or kterm . Beforedrawing graphics,plotfont -T tek willemit anescapesequencethatcausestheterminalemulator’s auxiliary Tektronixwindow, which is

Page 63: plotutils

Chapter6: Theplotfont Utility 58

normallyhidden,to popup. After thegraphicsaredrawn, anescapesequencethat returnscontrolto theoriginal VT100window will beemitted.TheTektronixwindow will remainon thescreen.

If thevalueof TERMis astringbeginningwith " kermit" , " ansi.sys" , or " nansi.sys" , it is takenasa sign that plotfont is running in the VT100 terminal emulatorprovided by the MS-DOSversionof kermit . Beforedrawing graphics,plotfont -T tek will emit anescapesequencethatswitchestheterminalemulatorto Tektronixmode. Also, someof theTektronixcontrolcodesemittedby plotfont -T tek will bekermit -specific.Therewill bea limited amountof colorsupport,which is not normally the case(the 16 ansi.sys colors will be supported). Afterdrawing graphics,plotfont -T tek will emit an escapesequencethat returnsthe emulatortoVT100mode.Thekey sequence‘ALT minus’ canbeemployedmanuallywithin kermit to switchbetweenthetwo modes.

Page 64: plotutils

Chapter7: Thespline Program 59

7 The spline Program

7.1 How to usespline

GNU spline is a programfor interpolatingbetweenthedatapointsin oneor moredatasets.Eachdatasetwould consistof valuesfor an independentvariableanda dependentvariable,whichmaybeavectorof specifiedfixedlength.Whendiscussinginterpolation,wecall thesevariables‘ B ’and‘ C ’, respectively. To emphasize:B is ascalar, but in generalthedependentvariable C maybeavector.

Thesimplestcaseis whenthereis asingleinputfile, which is in ASCII format,andthevector Cis one-dimensional.This is thedefault. For example,theinput file couldcontainthedataset

0.0 0.01.0 1.02.0 0.0

which arethecoordinates( BEDC ) of thedatapoints(0,0), (1,1), and(2,0). Datapointsdo not needto beon differentlines,nor do the B and C coordinatesof a datapoint needto beon thesameline.However, thereshouldbenoblanklinesin theinput if it is to beviewedasformingasingledataset.Also, by default the B coordinateshouldbemonotonicallyincreasing,sothat C maybeviewedasafunctionof B .

Youwouldconstructaspline(thegraphof an‘interpolatingfunction’) passingthroughthepointsin this datasetby doing

spline input_file > output_file

To produceaPostscriptplot of thesplinewith thegraph utility, youwoulddo

spline input_file | graph -T ps > output.ps

To displayasplineonanX Window Systemdisplay, youcoulddo

echo 0 0 1 1 2 0 | spline | graph -T X

Notice that the last exampleavoids the useof the input file altogether. spline will readfromstandardinput if no files are specifiedon the commandline, or if the specialfile name‘ - ’ isspecified.

What exactly doesspline do? First, it fits a curve (the graphof an interpolatingfunction)throughthepointsin thedataset.Thenit splits the interval over which the independentvariableBrangesinto 100 sub-intervals, and computesthe C valuesat eachof the 101 subdivision points.It thenoutputseachof thepairs( BEDC ). Thesearethecoordinatesof 101pointsthatlie alongacurvethat interpolatesbetweenthe points in the dataset. If thereis more thanonedatasetin the input(separatedby blanklines),eachdatasetis interpolatedseparately.

Youmayusethe‘ -n ’ optionto replace‘100’ by any otherpositive integer. Youmayalsousethe‘ -t ’ optionto specifyaninterpolationinterval thatdiffersfrom thedefault (theinterval overwhichtheindependentvariableranges).For example,thecommand

echo 0 0 1 1 2 0 | spline -n 20 -t 1.0 1.5 > output_file

will producea datasetconsistingof 21 (ratherthan101)datapoints,with B valuesspacedregularlybetween1.0and1.5(ratherthanbetween0.0and2.0). Thedatapointswill lie alongacurvepassingthrough(0,0),(1,1),and(2,0). Thiscurve will beaparabola.

Page 65: plotutils

Chapter7: Thespline Program 60

In general,theinterpolatingfunctionwill beapiecewisecubicspline.Thatis, betweeneachpairof adjacent‘knots’ (pointsin the input dataset),F will bea cubic functionof G . This functionwilldiffer, dependingon whichpairof knots F liesbetween.At eachknot,boththeslopeandcurvatureof thecubicpiecesto eithersidewill match.In mathematicalterms,theinterpolatingcurve will betwice continuouslydifferentiable.

spline supports‘adding tension’to the interpolatingcurve. A nonzerovaluefor the tensioncanbe specifiedwith the ‘ -T ’ option. For example,a splineunderconsiderabletensioncanbecomputedanddisplayedby doing

echo 0 0 1 0 2 0 | spline -T 10 | graph -T X

As thetensionparameteris increasedto positiveinfinity, thesplinewill convergeto apolygonalline.You aremeantto think of thesplineasbeingdrawn taut. Actually, tensionmaybenegative aswellaspositive. A splinewith negativetensionwill tendto bow outward,in factto oscillatesinusoidally.But asthetensiondecreasesto negative infinity, thespline,thoughoscillatory, will againconvergeto a polygonalline.

If thetensionis positive, its reciprocalwill bethemaximumrangeof theindependentvariableGover which the splinewill ‘lik e to curve’. Increasingthe tensionfar above zerowill accordinglyforce the splineto consistof shortcurved sections,centeredon the datapoints,andsectionsthatarealmoststraight. It follows that tensionis a ‘dimensionful’ quantity. If the tensionis nonzero,thenwhenthevaluesof the independentvariablearemultiplied by somecommonpositive factor,the tensionshouldbe divided by the samefactorto obtaina scaledversionof the original spline.If the tensionis zero(thedefault, or cubicsplinecase),thenthecomputationof thesplinewill beunaffectedby linearscalingof thedata.

In mathematicalterms,asplineundertensionwill satisfythedifferentialequation

FIH H H H = sgn(tension)tensionJKFLH Hbetweeneachsuccessive pair of knots. If the tensionequalszero,which is thedefault, the fourthderivative of F with respectto G will equalzeroat every point. In this case,F asa functionof G willreduceto a cubicpolynomialbetweeneachsuccessive pair of knots. But if thetensionis nonzero,F will not be a polynomial function of G . It may be expressedin termsof exponentialfunctions,however.

Irrespective of whetheror not the spline is undertension,you may specify the ‘ -p ’ option ifyou wish thesplineto bea periodicfunctionof G . This will only work if the F valuesfor thefirstandlastpointsin thedatasetareequal. Otherwise,it would make no senseto computea periodicinterpolation.

It is sometimesusefulto interpolatebetweendatapointsatthesametimeasthey aregeneratedbyanauxiliaryprogram.Thatis, it isusefulfor spline to functionasareal-timefilter. spline doesnotnormallyactasafilter, sincecomputinganinterpolatingcurve thatis assmoothaspossibleis aglobaltask.But if the‘ -f ’ optionis specified,spline will indeedfunctionasafilter. A differentinterpolationalgorithm(cubicBesselinterpolation,which is local ratherthanglobal)will beused.If ‘ -f ’ is specified,‘ -p ’ may not be specified. Also, if ‘ -f ’ is specifiedthen an interpolationinterval (a rangeof G values) mustberequestedexplicitly with the‘ -t ’ option.

Cubic Besselinterpolationis inherently lesssmooththan the constructionof a global cubicspline. If the‘ -f ’ optionis specified,theslopeof thesplineateachknotwill bechosenby fitting aparabolathroughthatknot,andthetwo adjacentknots.Theslopesof thetwo interpolatingsegments

Page 66: plotutils

Chapter7: Thespline Program 61

to eithersideof eachinterior knot will matchat thatknot,but typically their curvatureswill not. Inmathematicalterms,the interpolatingcurve will becontinuouslydifferentiable,but in generalnottwicecontinuouslydifferentiable.Thislossof differentiabilityis thepricethatispaidfor functioningasa real-timefilter.

7.2 Advanceduseof spline

Theprecedingsectionexplainshow spline canbeemployed to interpolatea function M of ascalarvariable N , in the casewhen M is a scalar. In this sectionwe explain how to performmoresophisticatedinterpolations.This includesmultidimensionalinterpolations,andinterpolationsthatarespliningsof curves,ratherthanof functions.

spline can handlethe casewhen M is a vector of arbitrary specifieddimensionality. Thedimensioncan be specifiedwith the ‘ -d ’ option. For example,an input file could containthemultidimensionaldataset

0.0 0.0 1.01.0 1.0 0.02.0 0.0 1.0

which arethecoordinates( NEOM ) of thedatapoints(0,0,1),(1,1,0),and(2,0,1).You would constructaspline(thegraphof aninterpolatingfunction)passingthroughthepointsin this datasetby doing

spline -d 2 input_file > output_file

Theoption ‘ -d 2’ is usedbecausein this example,thedependentvariable M is a two-dimensionalvector. Eachof the componentsof M will be interpolatedindependently, and the outputfile willcontainpointsthatlie alongthegraphof theresultinginterpolatingfunction.

Whendoingmultidimensionalsplining,youmayuseany of theoptionsthatapplyin thedefaultone-dimensionalcase.For example,the‘ -f ’ optionwill yield real-timecubicBesselinterpolation.As in theone-dimensionalcase,if the‘ -f ’ optionis usedthenthe‘ -t ’ optionmustbeusedaswell,to specifyaninterpolationinterval (a rangeof N values). The‘ -p ’ optionwill yield aperiodicspline,i.e., thegraphof a periodicvector-valuedfunction. For this, thefirst andlastdatasetM valuesmustbethesame.

spline canalso be usedto draw a curve througharbitrarily chosenpoints in the plane,orin generalthrougharbitrarilychosenpointsin P -dimensionalspace.Thisis notthesameassplining,at leastasthetermis conventionallydefined.Thereasonis that ‘splining’ refersto constructionofa function,ratherthantheconstructionof a curve thatmayor maynot bethegraphof a function.Not every curve is thegraphof a function.

Thefollowing exampleshows how youmay‘splineacurve’. Thecommand

echo 0 0 1 0 1 1 0 1 | spline -d 2 -a -s | graph -T X

will constructa curve in theplanethroughthe four points(0,0), (1,0), (1,1), and(0,1), andgraphit on an X Window Systemdisplay. The ‘ -d 2’ option specifiesthat the dependentvariable M istwo-dimensional.The ‘ -a ’ option specifiesthat N valuesaremissingfrom the input, andshouldbeautomaticallygenerated.By default, thefirst N valueis 0, thesecondis 1, etc. The‘ -s ’ optionspecifiesthatthe N valuesshouldbestrippedfrom theoutput.

Thesametechniquemaybeusedto splineaclosedcurve. For example,doing

echo 0 0 1 0 0 1 0 0 | spline -d 2 -a -s -p | graph -T X

Page 67: plotutils

Chapter7: Thespline Program 62

will constructandgrapha closed,lozenge-shapedcurve throughthe threepoints(0,0), (1,0), and(0,1). Theconstructionof a closedcurve is guaranteedby the ‘ -p ’ (i.e., ‘ --periodic ’) option,andby therepetitionof theinitial point (0,0)at theendof thesequence.

Whenspliningacurve,whetheropenorclosed,youmaywishtosubstitutethe‘ -A ’ optionfor the‘ -a ’ option. Like the‘ -a ’ option,the‘ -A ’ optionspecifiesthat Q valuesaremissingfrom theinputandshouldbe automaticallygenerated.However, the incrementfrom one Q valueto thenext willbethedistancebetweenthecorrespondingvaluesof R . This schemefor generatingQ values, whenconstructingacurve throughasequenceof datapoints,is theschemethatis usedin thewell knownFITPACK subroutinelibrary. It isprobablythebestapproachwhenthedistancesbetweensuccessivepointsfluctuateconsiderably.

A curve througha sequenceof points in the plane,whetheropenor closed,may crossitself.Someinterestingvisual effectscanbe obtainedby addingnegative tensionto sucha curve. Forexample,doing

echo 0 0 1 0 1 1 0 0 | spline -d 2 -a -s -p -T -14 -n 500 | graph -T X

will constructa closedcurve throughthe threepoints(0,0), (1,0), and(0,1), which is woundintocurlicues. The ‘ -n 500 ’ option is includedbecausetherearesomany windings. It specifiesthat501pointsshouldbegenerated,which is enoughto draw asmoothcurve.

7.3 spline command-lineoptions

Thespline programwill interpolatevector-valuedfunctionsof ascalarvariableQ , andcurvesinS-dimensionalspace.Thealgorithmsusedby spline aresimilar to thosediscussedin D. Kincaid

and[E.] W. Cheney, NumericalAnalysis(2nded.,Brooks/Cole,1996),section6.4,andC. deBoor,A PracticalGuideto Splines(Springer-Verlag,1978),Chapter4.

Input file namesmaybespecifiedanywhereon thecommandline. That is, therelative orderoffont namesandcommand-lineoptionsdoesnot matter. If no file namesarespecified,or the filename‘ - ’ is specified,thestandardinput is read.

An input file maycontainmorethana singledataset.Unlessthe‘ -a ’ or ‘ -A ’ optionsareused(seebelow), eachdatasetis expectedto consistof a sequenceof datapoints,given asalternatingQ and R values. Q is thescalarindependentvariable,and R is thevector-valueddependentvariable.Thedimensionalityof R is specifiedwith the‘ -d ’ option(thedefault is 1).

If the input file is in ASCII format (the default), its datasetsareseparatedby blank lines. Aninput file may also containany numberof commentlines, which must begin with the commentcharacter‘#’ . Commentlinesareignored.They arenot treatedasblank,i.e., they donot interruptadatasetin progress.

Theoptionsto spline arelistedbelow. Therearethreesortsof option:

1. Optionsspecifyingthetypeof interpolationto beperformedon eachdataset.

2. Optionsspecifyingtheinput or outputformat.

3. Optionsrequestinginformation(e.g.,‘ --help ’).

Optionsthat take an argumentare followed, in parentheses,by the type anddefault valueof theargument.

Thefollowing optionsspecifythetypeof interpolationto beperformedoneachdataset.

Page 68: plotutils

Chapter7: Thespline Program 63

‘ -f ’‘ --filter ’

Usea local interpolationalgorithm(thecubicBesselalgorithm),sothatspline canbe usedasa real-timefilter. The slopeof the interpolatingcurve at eachpoint in adatasetwill be chosenby fitting a quadraticfunction throughthat point andthe twoadjacentpoints in the dataset. If ‘ -f ’ is specifiedthen the ‘ -t ’ option, otherwiseoptional,mustbeusedaswell. Also, if ‘ -f ’ is specifiedthenthe‘ -k ’, ‘ -p ’, and‘ -T ’optionsmaynotbeused.

If ‘ -f ’ is not specified,thena different(global)interpolationalgorithmwill beused.

‘ -k k ’‘ --boundary-cond iti on k ’

(Float,default 1.0.) Settheboundaryconditionparameterfor eachconstructedsplineto bek . In eachof its components,thesplinewill satisfythetwo boundaryconditionsTIU U [0] = V TIU U [1] and TIU U [ W ] = V TLU U [ WYX 1]. Here T [0] and T [1] signify the valuesof aspecifiedcomponentof thevector-valueddependentvariableT atthefirst two pointsofadataset,and T [ WZX 1] and T [ W ] thevaluesat thelasttwo points.Settingk to zerowillyield a ‘natural’ spline,i.e.,onethathaszerocurvatureat thetwo endsof thedataset.The‘ -k ’ optionmaynotbeusedif ‘ -f ’ or ‘ -p ’ is specified.

‘ -n n’‘ --number-of-int erv al s n’

(Positive integer, default 100.) Subdivide theinterval over which interpolationoccursinto n subintervals. The numberof datapointscomputed,andwritten to the output,will be W +1.

‘ -p ’‘ --periodic ’

Constructaperiodicspline. If thisoptionis specified,the T valuesfor thefirst andlastpointsin eachdatasetmustbe equal. The ‘ -f ’ and‘ -k ’ optionsmaynot be usedif‘ -p ’ is specified.

‘ -T tension’‘ --tension tension’

(Float,default0.0.) Setthetensionin eachinterpolatingsplineto betension. Betweeneachpair of successive points in a dataset,the constructedspline will satisfy thedifferential equation TIU U U U = sgn(tension)tension[ TLU U in eachof its components. Iftensionequalszero,thesplinewill bepiecewisecubic.As tensionincreasesto positiveinfinity, thesplinewill convergeto apolygonalline. The‘ -T ’ optionmaynotbeusedif ‘ -f ’ is specified.

‘ -t tmin tmax [ tspacing] ’‘ --t-limits tmin tmax [ tspacing] ’

For eachdataset,set the interval over which interpolationoccursto be the intervalbetweentmin andtmax. If tspacingis not specified,the interval will bedivided intothenumberof subintervalsspecifiedby the‘ -n ’ option. If the‘ -t ’ optionis notused,theinterval overwhich interpolationoccurswill betheentirerangeof theindependentvariablein thedataset.The‘ -t ’ optionmustalwaysbeusedif the‘ -f ’ optionis usedto requestfilter-like behavior (seeabove).

Page 69: plotutils

Chapter7: Thespline Program 64

Thefollowing optionsspecifytheformatof theinput file(s)andtheoutputfile.

‘ -d dimension’‘ --y-dimension dimension’

(Integer, default1.) Setthedimensionalityof thedependentvariable\ in theinputandoutputfiles to bedimension.

‘ -I data-format’‘ --input-format data-format’

(Character, default ‘a’.) Setthedataformatfor theinputfile(s) to bedata-format. Thepossibledataformatsareasfollows.

‘a’ ASCII format. Eachfile is a sequenceof floating point numbers,inter-pretedasthe ] and \ coordinatesof thesuccessivedatapointsin adataset.If \ is ^ -dimensional,therewill be ^ +1 numbersfor eachpoint. The ]and \ coordinatesof apointneednotappearon thesameline, andpointsneednot appearon different lines. But if a blank line occurs(i.e., twonewlines in successionareseen),it is interpretedastheendof a dataset,andthebeginningof thenext.

‘ f ’ Singleprecisionbinary format. Eachfile is a sequenceof floatingpointnumbers,interpretedas the ] and \ coordinatesof the successive datapointsin adataset.If \ is ^ -dimensional,therewill be ^ + 1 numbersforeachpoint. Successivedatasetsareseparatedbyasingleoccurrenceof thequantityFLT_MAX, whichis thelargestpossiblesingleprecisionfloatingpoint number. On mostmachinesthis is approximately3 _ 4 ` 10a�b .

‘d’ Doubleprecisionbinaryformat. Eachfile is a sequenceof doublepreci-sionfloatingpoint numbers,interpretedasthe ] and \ coordinatesof thesuccessive datapoints in a dataset.If \ is ^ -dimensional,therewill be^ +1 numbersfor eachpoint. Successivedatasetsareseparatedbyasingleoccurrenceof thequantityDBL_MAX, whichis thelargestpossibledoubleprecisionfloatingpointnumber. On mostmachinesthis is approximately1 _ 8 ` 10a�c�b .

‘ i ’ Integerbinary format. Eachfile is a sequenceof integers,interpretedasthe ] and \ coordinatesof thesuccessive datapointsin a dataset.If \ is^ -dimensional,therewill be ^ + 1 numbersfor eachpoint. Successivedatasetsareseparatedby a singleoccurrenceof thequantityINT_MAX,which is thelargestpossibleinteger. On mostmachinesthis is 2adfe 1.

‘ -a [ stepsize[ lower limit ]] ’‘ --auto-abscissa [ stepsize[ lower limit ]] ’

(Floats, defaults 1.0 and 0.0.) Automatically generatevaluesfor the independentvariable( ] ). Irrespective of dataformat (‘a’, ‘ f ’, ‘d’, or ‘ i ’ ), this option specifiesthat the valuesof the independentvariable( ] ) are missingfrom the input file: thedataset(s)to be readcontainonly valuesof thedependentvariable( \ ), sothat if \ is^ -dimensional,therewill beonly ^ numbersfor eachpoint. Theincrementfrom each] valueto thenext will bestepsize, andthefirst ] valuewill belower limit .

Page 70: plotutils

Chapter7: Thespline Program 65

‘ -A ’‘ --auto-dist-abs cis sa ’

Automaticallygeneratevaluesfor theindependentvariable( g ). This is a variantformof the ‘ -a ’ option. The incrementfrom eachg valueto thenext will be thedistancebetweenthe correspondingh values,andthe first g valuewill be 0.0. This option isusefulwheninterpolatingcurvesratherthanfunctions(seeSection7.2[AdvancedUseof spline],page61).

‘ -O data-format’‘ --output-format data-format’

(Character, default ‘a’.) Setthedataformatfor theoutputfile to bedata-format. Theinterpretationof thedata-formatargumentis thesameasfor the‘ -I ’ option.

‘ -P significant-digits’‘ --precision significant-digits’

(Positive integer, default 6.) Setthenumericalprecisionfor the g and h valuesin theoutputfile to besignificant-digits. This takeseffect only if theoutputfile is written in‘a’ format,i.e., in ASCII.

‘ -s ’‘ --suppress-absc iss a’

Omit the independentvariable g from theoutputfile; for eachpoint, supplyonly thedependentvariableh . If h is i -dimensional,therewill be only i numbersfor eachpoint, not i +1. This option is usefulwheninterpolatingcurvesratherthanfunctions(seeSection7.2[AdvancedUseof spline],page61).

Thefollowing optionsrequestinformation.

‘ --help ’ Print a list of command-lineoptions,andthenexit.

‘ --version ’Print theversionnumberof spline andtheplotting utilities package,andexit.

Page 71: plotutils

Chapter8: Theode Program 66

8 The ode Program

The GNU ode utility canproducea numericalsolutionto the initial valueproblemfor manysystemsof first-orderordinarydifferentialequations(ODE’s). ode canalsobeusedtosolvesystemsof higher-orderODE’s, sincea simpleprocedureconvertsan j ’ th-orderequationinto j first-orderequations.Theoutputof ode caneasilybe pipedto graph , so thatoneor moresolutioncurvesmaybeplottedasthey aregenerated.

Threedistinct schemesfor numericalsolution are implemented:Runge–Kutta–Fehlberg (thedefault), Adams–Moulton,andEuler. The Runge–Kutta–Fehlberg andAdams–Moultonschemesareavailablewith adaptive stepsize.

8.1 Mathematicalbasics

We begin with somestandarddefinitions. A differential equationis an equationinvolving anunknown functionandits derivatives. A differentialequationis ordinary if theunknown functiondependson only oneindependentvariable,oftendenotedk . Theorder of thedifferentialequationis the order of the highest-orderderivative in the equation. One speaksof a family, or systemof equationswhen more than one equationis involved. If the equationsare dependenton oneanother, they aresaidto becoupled. A solutionis any functionsatisfyingtheequations.An initialvalueproblemis presentwhenthereexist subsidiaryconditionson the unknown function anditsderivatives,all of which aregivenat thesamevalueof theindependentvariable. In principle,suchan‘initial condition’ specifiesauniquesolution.Questionsabouttheexistenceanduniquenessof asolution,alongwith further terminology, arediscussedin any introductorytext. (SeeChapter1 ofBirkhoff andRota’sOrdinaryDifferentialEquations. For thisandotherreferencesrelevantto ode ,seeSection8.9 [ODE Bibliography],page83.)

In practicalproblems,thesolutionof a differentialequationis usuallynot expressiblein termsof elementaryfunctions.Hencetheneedfor anumericalsolution.

A numericalschemefor solving an initial value problemproducesan approximatesolution,usingonly functionalevaluationsand the operationsof arithmetic. ode solvesfirst-orderinitialvalueproblemsof theform:lnm = o ( kEp l pq psrsrsrtpvu )q m = w ( kxp l pqnpsrsrsrypvu )

.

.

.u m = z ( kEp l pq psrsrsrypvu )giventheinitial valuesfor eachdependentvariableat theinitial valueof theindependentvariablek ,i.e., l ( { ) = |q ( { ) = }

.

.

.u ( { ) = ~k = {where{np�|tpv}ypsrsrsrypv~ areconstants.

Page 72: plotutils

Chapter8: Theode Program 67

For ode to be able to solve sucha problemnumerically, the functions � ���K�s�s�s�t��� must beexpressed,using the usualoperators(plus, minus, multiplication, division, and exponentiation),in termsof certainbasic functionsthat ode recognizes. Theseare the samefunctionsthat theplotting programgnuplot recognizes.Moreover, eachof � ���K�s�s�s����� mustbe given explicitly.ode cannotdealwith a systemin which oneor moreof the first derivatives is definedimplicitlyratherthanexplicitly.

All schemesfor numericalsolutioninvolve thecalculationof anapproximatesolutionatdiscretevaluesof theindependentvariable� , wherethe‘stepsize’(thedifferencebetweenany twosuccessivevaluesof � , usuallydenoted� ) may be constantor chosenadaptively. In general, asthe stepsizedecreasesthesolutionbecomesmoreaccurate.In ode , thestepsizecanbeadjustedby theuser.

8.2 Simpleexamplesusingode

The following examplesshouldillustratetheprocedureof statingan initial valueproblemandsolvingit with ode . If theseexamplesaretooelementary, seeSection8.8[InputLanguage],page79,for a formal specificationof theode input language.Thereis alsoadirectorycontainingexamplesof ode input, which is distributed alongwith the GNU plotting utilities. On most systemsit isinstalledas‘ /usr/share/ode ’ or ‘ /usr/local/shar e/ ode’.

Ourfirst exampleis asimpleone,namely�I� ( � ) = � ( � )with theinitial condition� (0) = 1

Thesolutionto thisdifferentialequationis� ( � ) = ��� .In particular� (1) = ��� = 2 � 718282

to sevendigitsof accuracy.

You mayobtainthis resultwith theaid of ode by typing on thecommandline thesequenceofcommands

odey’ = yy = 1print t, ystep 0, 1

Two columnsof numberswill appear. Eachline will show thevalueof theindependentvariable� ,andthevalueof thevariable� , as � is ‘stepped’from 0 to 1. Thelastline will be

1 2.718282

asexpected.You mayusethe‘ -p ’ optionto changetheprecision.If, for example, you type‘ode-p 10 ’ ratherthan‘ode ’, you will get tendigits of accuracy in theoutput,ratherthanseven (thedefault).

After theabove output,ode will wait for furtherinstructions.Enteringfor exampletheline

step 1, 0

shouldyield two morecolumnsof numbers,containingthevaluesof � and � thatarecomputedwhen� is steppedbackfrom 1 to 0. Youcouldtypeinstead

Page 73: plotutils

Chapter8: Theode Program 68

step 1, 2

to increaseratherthan decrease� . To exit ode , you would type a line containingonly ‘ . ’, i.e.asingleperiod,andtap ‘return’. ode will alsoexit if it seesan end-of-file indicator in its inputstream,whichyoumaysendfrom your terminalby typingcontrol-D.

Eachline of the precedingexampleshouldbe self-explanatory. A ‘step ’ statementsetsthebeginningandtheendof an interval over which the independentvariable(here,� ) will range,andcausesode to setthenumericalschemein motion. Theinitial valueappearingin thefirst ‘step ’statement(i.e.,0) andtheassignmentstatement

y = 1

are equivalent to the initial condition � (0) = 1. The statements‘y’ = y ’ and ‘y = 1’ are verydifferent: ‘y’ = y ’ definesa way of computingthe derivative of � , while ‘y = 1’ setsthe initialvalueof � . Whenevera‘step ’ statementis encountered,ode triesto steptheindependentvariablethroughtheinterval it specifies.Whichvaluesareto beprintedateachstepis specifiedby themostrecent‘print ’ statement.For example,

print t, y, y’

would causethecurrentvalueof the independentvariable� , thevariable� , andits derivative to beprintedat eachstep.

To illustrateode ’s ability to take its input or the initial part of its input from a file, you couldprepareafile containingthefollowing lines:

# an ode to Eulery = 1y’ = yprint t, y, y’

Call this file ‘euler ’. (The‘#’ line is acommentline, whichmayappearatany point. Everythingfrom the‘#’ to the endof the line on which it appearswill be ignored.) To processthis file withode , youcouldtypeon your terminal

ode -f eulerstep 0, 1

Thesetwo linescauseode to readthefile ‘euler ’, andthesteppingto takeplace.Youwill now getthreequantities( � , � , and �L� ) printedateachof thevaluesof � between0 and1. At theconclusionofthestepping,ode will wait for any furthercommandsto beinput from theterminal. This exampleillustratesthat

ode -f euler

is notequivalentto

ode < euler

The latter would causeode to take all its input from the file ‘euler ’, while the former allowssubsequentinput from theterminal. For the latter to produceoutput,you would needto includea‘step ’ line at theendof thefile. Youwouldnotneedto includea ‘ . ’ line, however. ‘ . ’ is usedtoterminateinput only wheninput is beingreadfrom a terminal.

A secondsimpleexampleinvolvesthenumericalsolutionof asecond-orderdifferentialequation.Considertheinitial valueproblem

�I� � ( � ) = ��� ( � )� (0) = 0�I� (0) = 1

Page 74: plotutils

Chapter8: Theode Program 69

Its solutionwouldbe� ( � ) = sin( � )To solve this problemusingode , you mustexpressthis second-orderequationastwo first-orderequations.Towardthis endyou would introducea new function,called ��� say, of the independentvariable� . Thepairof equations�I� = ������n� = � �wouldbeequivalentto thesingleequationabove. Thissortof reductionof an � ’ th orderproblemto� first orderproblemsis a standardtechnique.

To plot thevariable� asa functionof thevariable� , youcouldcreatea file containingthelines# sine : y’’(t) = -y(t), y(0) = 0, y’(0) = 1sine’ = cosinecosine’ = -sinesine = 0cosine = 1print t, sine

( � and ��� havebeenrenamedsineandcosine, sincethatis whatthey will be.) Call thisfile ‘sine ’.To displaythe generateddatapointson an X Window Systemdisplayasthey aregenerated,youwould type

ode -f sine | graph -T X -x 0 10 -y -1 1step 0, 2*PI.

After you type the ode line, graph -T X will popup a window, andafter you type the ‘step ’line, the generateddatasetwill be drawn in it. The ‘ -x 0 10 ’ and ‘ -y -1 1’ options,which setthe boundsfor the two axes,arenecessaryif you wish to displaypoints in realtime: asthey aregenerated.If the axis boundswerenot specifiedon the commandline, graph -T X would waituntil all pointsarereadfrom theinput beforedeterminingthebounds,anddrawing theplot.

A slight modificationof this example,showing how ode cangenerateseveraldatasetsin suc-cessionandplot themon thesamegraph,would bethefollowing. Supposethatyou typeon yourterminalthefollowing lines.

ode -f sine | graph -T X -C -x 0 10 -y -1 1step 0, PIstep PI, 2*PIstep 2*PI, 3*PI.

Thenthesinecurvewill betracedout in threestages.Sincetheoutputfrom each‘step ’ statementendswith a blankline, graph -T X will treateachsectionof thesinecurve asa differentdataset.If you areusinga color display, eachof thethreesectionswill beplottedin a differentcolor. Thisis a featureprovidedby graph , whichnormallychangesits linemodeaftereachdatasetit reads.Ifyoudo not like this feature,youmayturn it off by usinggraph -T X -B insteadof graph -T X.

In the above examples,you could useany of the othervariantsof graph insteadof graph-T X. For example,youcouldusegraph -T ps to obtainaplot in encapsulatedPostscriptformat,by typing

ode -f sine | graph -T ps > plot.psstep 0, 2*PI.

Page 75: plotutils

Chapter8: Theode Program 70

You shouldnote that of the variantsof graph , the variantsgraph -T png , graph -T pnm,graph -T gif , graph -T svg , graph -T ai , graph -T ps , graph -T cgm, graph -Tfig , graph -T pcl and graph -T hpgl do not produceoutput in real time, even when theaxisboundsarespecifiedwith the‘ -x ’ and‘ -y ’ options.Soif any of thesevariantsis used,theplotwill beproducedonly wheninput from ode is terminated,whichwill occurwhenyou type‘ . ’.

In theprecedingexamples,thederivativesof thedependentvariableswerespecifiedby compara-tively simpleexpressions.They areallowedto bearbitrarilycomplicatedfunctionsof thedependentvariablesandthe independentvariable. They may alsoinvolve any of the functionsthat arebuiltinto ode . ode hasa fair numberof functionsbuilt in, includingabs , sqrt , exp , log , log10 ,sin , cos , tan , asin , acos , atan , sinh , cosh , tanh , asinh , acosh , andatanh . Lessfa-miliar functionswhicharebuilt into it arebesj0 , besj1 , besy0 , besy1 , erf , erfc , inverf ,lgamma, gamma, norm , invnorm , ibeta , andigamma. Thesehave thesamedefinitionsasintheplotting programgnuplot . (All functionstake a singleargument,exceptfor ibeta , whichtakesthree,andigamma, which takestwo). ode alsoknows themeaningof theconstant‘PI ’, astheabove examplesshow. Thenamesof theprecedingfunctionsarereserved,so,e.g.,‘cos ’ and‘sin ’ maynotbeusedasnamesfor variables.

Other than the restrictionof avoiding reserved namesand keywords, the namesof variablesmay be chosenarbitrarily. Any sequenceof alphanumericcharactersstartingwith an alphabeticcharactermaybeused;thefirst 32 charactersaresignificant. It is worth notingthatode identifiestheindependentvariableby thefactthatit is (or shouldbe)theonly variablethathasnotappearedontheleft sideof a differentialequationor aninitial valueassignment.If thereis morethanthanonesuchvariablethenno steppingtakesplace;instead,anerrormessageis printed. If thereis no suchvariable,adummyindependentvariableis inventedandgiventhename‘ (indep) ’, internally.

8.3 Additional examplesusingode

We explain herehow to usesomeadditionalfeaturesof ode . However, the discussionbelowdoesnot cover all of its capabilities.For a completelist of command-lineoptions,seeSection8.4[odeInvocation],page73.

It is easyto useode to createplotsof greatbeauty. An examplewould bea plot of a strangeattractor, namelytheLorenzattractor. Supposethatafile named‘ lorenz ’ containsthefollowinglines.

# The Lorenz model, a system of three coupled ODE’s with parameter r.x’ = -3*(x-y)y’ = -x*z+r*x-yz’ = x*y-z

r = 26x = 0; y = 1; z = 0

print x, ystep 0, 200

Thenexecutingthecommand

ode < lorenz | graph -T X -C -x -10 10 -y -10 10

wouldproduceaplot of theLorenzattractor(strictly speaking,aplot of oneof its two-dimensionalprojections). You may producea Postscriptplot of the Lorenz attractor, and print it, by doingsomethinglike

Page 76: plotutils

Chapter8: Theode Program 71

ode < lorenz | graph -T ps -x -10 10 -y -10 10 -W 0 | lpr

The ‘ -W 0’ (“zero width”) option requeststhat graph -T ps usethe thinnestline possible,toimprove thevisualappearanceof theplot onaprinteror otherPostscriptdevice.

Besidesplotting a visually striking objectin realtime, theLorenzattractorexampleshows howstatementsmaybeseparatedby semicolons,ratherthanappearingon differentlines. It alsoshowshow to usesymbolicconstants.In thedescriptionreadby ode theparameter� is a variablelike � ,� , and � . But unlike themit is not updatedduringstepping,sinceno formulafor its derivative ��� isgiven.

Oursecondexampledealswith theinteractiveconstructionof a‘phaseportrait’: asetof solutioncurveswith differentinitial conditions.Phaseportraitsareof paramountinterestin thequalitativetheoryof differentialequations,andalsopossessæstheticappeal.

Since a descriptionread by ode may contain any numberof ‘step ’ statements,multiplesolutioncurvesmay be plottedin a singlerun. The mostrecent‘print ’ statementwill be usedwith each‘step ’ statement.In practice, a phaseportraitwould bedrawn from a few well-chosensolutioncurves.Choosingagoodsetof solutioncurvesmayrequireexperimentation,whichmakesinteractivity andreal-timeplottingall-important.

As anexample,consideraso-calledLotka–Volterrapredator–prey model.Supposethatin alaketherearetwo speciesof fish: A (theprey) who liveby eatingaplentiful supplyof plants,andB (thepredator)whoeatA. Let � ( � ) bethepopulationof A and � ( � ) thepopulationof B at time � . A crudemodelfor theinteractionof A andB is givenby theequations

� � = � ( �¡ £¢ � )� � = � ( ¤E�¥ §¦ )where �n¨�¢�¨v¤y¨v¦ arepositive constants.To draw a phaseportrait for this systeminteractively, youcouldtype

ode | graph -T X -C -x 0 5 -y 0 5x’ = (a - b*y) * xy’ = (c*x - d) * ya = 1; b = 1; c = 1; d = 1;print x, yx = 1; y = 2step 0, 10x = 1; y = 3step 0, 10x = 1; y = 4step 0, 10x = 1; y = 5step 0, 10.

Four curveswill bedrawn in succession,oneper ‘step ’ line. They will beperiodic;this period-icity is similar to the fluctuationsbetweenpredatorandprey populationsthat occurin real-worldecosystems.On a color displaythecurveswill appearin differentcolors,sinceby default, graphchangesthe linemodebetweendatasets.That featuremaybeturnedoff by usinggraph -T X -Bratherthangraph -T X.

It is sometimesusefulto useode andgraph to plot discretepoints,whicharenot joinedby linesegmentsto form acurve. Our third exampleillustratesthis. Supposethefile ‘atwoods ’ containsthelines

Page 77: plotutils

Chapter8: Theode Program 72

m = 1M = 1.0625a = 0.5; adot = 0l = 10; ldot = 0

ldot’ = ( m * l * adot * adot - M * 9.8 + m * 9.8 * cos(a) ) / (m + M)l’ = ldotadot’ = (-1/l) * (9.8 * sin(a) + 2 * adot * ldot)a’ = adot

print l, ldotstep 0, 400

Thefirst few linesdescribethefunctioningof aso-calledswingingAtwood’smachine.An ordinaryAtwood’s machineconsistsof a taut cord drapedover a pulley, with a massattachedto the cordat eachend. Normally, theheavier mass( © ) would win againstthe lighter mass( ª ), anddraw itupward. A swingingAtwood’s machineallows thelighter massto swingbackandforth aswell asmovevertically.

The‘print l, ldot ’ statementrequeststhattheverticalpositionandverticalvelocity of thelightermassbeprintedoutat eachstep.If you run thecommand

ode < atwoods | graph -T X -x 9 11 -y -1 1 -m 0 -S 1 -X l -Y ldot

youwill obtainareal-timeplot. The‘ -m 0’ optionrequeststhatsuccessivedatapointsnotbejoinedby line segments,andthe ‘ -S 1’ option requeststhat plotting symbol#1 (adot) be plottedat thelocationof eachpoint. As youwill seeif yourunthiscommand,theheavy massdoesnotwin againstthelightermass.Insteadthemachineoscillatesnon-periodically. Sincethemotionis non-periodic,theplot benefitsfrom beingdrawn asasequenceof unconnectedpoints.

We concludeby mentioninga few featuresof ode that may be useful when things are notgoingquite right. Oneof themis the ‘examine ’ statement.It maybeusedto discover pertinentinformationaboutany variablein asystem.For details,seeSection8.8[Input Language],page79.

Anotherusefulfeatureis thatthe‘print ’ statementmaybeusedto print outmorethanjust thevalueof avariable.As wehaveseen,if thenameof thevariableis followedby ‘ ’ ’, thederivativeofthevariablewill beprintedinstead.In a similar way, following thevariablenamewith ‘?’, ‘ ! ’, or‘ ˜ ’ printsrespectively therelativesingle-steperror, theabsolutesingle-steperror, or theaccumulatederror(notcurrentlyimplemented).Thesequantitiesarediscussedin Section8.6[NumericalError],page75.

The‘print ’ statementmaybemorecomplicatedthanwasshown in theprecedingexamples.Its generalstructureis

print <pr-list> [every <const>] [from <const>]

Thebracket notation‘ [ . . . ] ’ meansthat theenclosedstatementsareoptional. Until now we havenotmentionedthe‘every ’ clauseor the‘ from ’ clause.The<pr-list> is familiar, however; itis simply acomma-separatedlist of variables.For example,in thestatement

print t, y, y’ every 5 from 1

the <pr-list> is <t, y, y’> . The clauses‘every 5’ and ‘ from 1’ specify that printingshouldtake placeafter every fifth step,andthat the printing shouldbegin whenthe independentvariable« reaches1. An ‘every ’ clauseis usefulif you wish to ‘thin out’ theoutputgeneratedbya ‘step ’ statement,anda ‘ from ’ clauseis usefulif you wish to view only thefinal portionof asolutioncurve.

Page 78: plotutils

Chapter8: Theode Program 73

8.4 ode command-lineoptions

Thecommand-lineoptionsto ode arelistedbelow. Thereareseveralsortsof option:

1. Optionsaffectingtheway in which input is read.

2. Optionsaffectingtheformatof theoutput.

3. Optionsaffecting thechoiceof numericalsolutionscheme,andtheerrorboundsthatwill beimposedon it.

4. Optionsthatrequestinformation.

Thefollowing optionaffectstheway input is read.

‘ -f filename’‘ --input-file filename’

Readinput from filenamebeforereadingfrom standardinput.

Thefollowing optionsaffect theoutputformat.

‘ -p significant-digits’‘ --precision significant-digits’

(Positive integer, default6.) Whenprintingnumericalresults,useaprecisionspecifiedby significant-digits. If thisoptionis given,theprint formatwill bescientificnotation.

‘ -t ’‘ --title ’

Print a title line at theheadof theoutput,namingthecolumns.If this optionis given,theprint formatwill bescientificnotation.

Thefollowing optionsspecifythenumericalintegrationscheme.Only oneof thethreebasicoption‘ -R ’, ‘ -A ’, and‘ -E ’ maybespecified.Thedefault is ‘ -R ’ (Runge–Kutta–Fehlberg).

‘ -R [ stepsize] ’‘ --runge-kutta [ stepsize] ’

Usea fifth-order Runge–Kutta–Fehlberg algorithm,with an adaptive stepsizeunlessa constantstepsizeis specified. Whena constantstepsizeis specifiedandno erroranalysisis requested,thenaclassicalfourth-orderRunge–Kuttaschemeis used.

‘ -A [ stepsize] ’‘ --adams-moulton [ stepsize] ’

Use a fourth-orderAdams–Moultonpredictor–corrector scheme,with an adaptivestepsizeunlessa constantstepsize,stepsize, is specified.TheRunge–Kutta–Fehlbergalgorithmis usedto getpast‘bad’ points(if any).

‘ -E [ stepsize] ’‘ --euler [ stepsize] ’

Usea ‘quick anddirty’ Euler scheme,with a constantstepsize.Thedefault valueofstepsizeis 0.1. Not recommendedfor seriousapplications.

Theerrorboundoptions‘ -r ’ and‘ -e ’ (seebelow) maynotbeusedif ‘ -E ’ is specified.

‘ -h hmin [ hmax] ’‘ --step-size-bou nd hmin [ hmax] ’

Usealowerboundhmin onthestepsize.Thenumericalschemewill notlet thestepsizegobelow hmin. Thedefault is to allow thestepsizeto shrinkto themachinelimit, i.e.,

Page 79: plotutils

Chapter8: Theode Program 74

theminimumnonzerodouble-precisionfloatingpointnumber. Theoptionalargumenthmax, if included,specifiesamaximumvaluefor thestepsize.It isusefulin preventingthenumericalroutinefrom skippingquickly over aninterestingregion.

Thefollowing optionssettheerrorboundson thenumericalsolutionscheme.

‘ -r rmax [ rmin] ’‘ --relative-erro r-b ound rmax [ rmin] ’

‘ -e emax[ emin] ’‘ --absolute-erro r-b ound emax[ emin] ’

The‘ -r ’ optionsetsanupperboundontherelativesingle-steperror. If the‘ -r ’ optionis used,therelative single-steperrorin any dependentvariablewill neverexceedrmax(the default for which is 10¬L­ ). If this shouldoccur, the solutionwill be abandonedandanerrormessagewill beprinted.If thestepsizeis notconstant,thestepsizewill bedecreased‘adaptively’, sothattheupperboundonthesingle-steperroris notviolated.Thus, choosinga smaller upperbound on the single-steperror will causesmallerstepsizesto be chosen.A lower boundrmin may optionally be specified,to suggestwhenthestepsizeshouldbe increased(thedefault for rmin is rmax/1000). The‘ -e ’option is similar to ‘ -r ’, but boundsthe absoluteratherthanthe relative single-steperror.

‘ -s ’‘ --suppress-erro r-b ound ’

Suppresstheceilingonsingle-steperror, allowing ode to continueevenif this ceilingis exceeded.Thismayresultin largenumericalerrors.

Finally, thefollowing optionsrequestinformation.

‘ --help ’ Print a list of command-lineoptions,andthenexit.

‘ --version ’Print theversionnumberof ode andtheplotting utilities package,andexit.

8.5 Diagnosticmessages

ode is alwaysin oneof two states:® Readinginput. Theinputincludesaspecificationof asystemof ordinarydifferentialequations,togetherwith instructionsfor solvingit numerically:a ‘print ’ line anda ‘step ’ line.® Numericallysolvingasystem,andprinting theresultingoutput.

ode movesfrom thefirst to thesecondstateafter it seesandprocessesa ‘step ’ line. It returnstothefirst stateafterthegeneratedoutputhasbeenprinted.Errorsmayoccurin the‘reading’ stateorthe‘solving’ state,andmayterminatecomputationsor evencauseode to exit. Wenow explain thepossiblesortsof error.

While readinginput,ode mayencounterasyntaxerror: anungrammaticalline thatit is unableto parse.(For asummaryof its inputgrammar, seeSection8.8[Input Language],page79.) If so, itemitstheerrormessage

ode::nnn: syntax error

where‘nnn ’ is thenumberof the line containingthe error. Whenthe ‘ -f filename ’ option isusedto specifyaninputfile, theerrormessagewill read

Page 80: plotutils

Chapter8: Theode Program 75

ode:filename:nn n: syntax error

for errorsencounteredinsidethe input file. Subsequently, whenode begins readingthestandardinput, line numberswill startoveragainfrom 1.

No effort is madeto recover from syntaxerrorsin theinput. However, thereis a meagereffortto resynchronize,sothatmorethanonesyntaxerrorin afile maybefoundat thesametime.

It is alsopossiblethata fatalarithmeticexception(suchasadivisionby zero,or afloatingpointoverflow) may occurwhile ode is readinginput. If suchan exceptionoccurs,ode will print an“Floating point exception”errormessageandexit. Arithmetic exceptionsaremachine-dependent.On somemachines,theline

y = 1/0

would induceanarithmeticexception.Also onsomemachines(notnecessarilythesameones),thelines

y = 1e100z = yˆ4

would inducean arithmeticexception. That is becauseon most machines,the doubleprecisionquantitiesthatode usesinternallyarelimited to amaximumsizeof approximately1 ¯ 8 ° 10±�²�³ .

When ode is in the ‘solving’ state,i.e., computinga numericalsolution, similar arithmeticexceptionsmayoccur. If so,thesolutionwill beinterruptedandamessageresembling

ode: arithmetic exception while calculating y’

will beprinted. However, ode will not exit; theexceptionwill be ‘caught’. ode itself recognizesthefollowing exceptionalconditions:squarerootof anegative number, logarithmof anon-positivenumber, andnegative numberraisedto a non-integer power. ode will catchany of theseopera-tions beforeit is performed,andprint an error messagespecifyingwhich illegal operationit hasencountered.

ode: square root of a negative number while calculating y’

wouldbea typicalerrormessage.

If themachineonwhichode isrunningsupportsthe‘matherr ’ facility for reportingerrorsin thecomputationof standardmathematicalfunctions,it will beused.This facility reportsdomainerrorsandrangeerrors(overflows,underflows,andlossesof significance)thatcouldoccurwhenevaluatingsuchfunctionsas‘ log ’, ‘gamma’, etc.;again,beforethey areperformed.If thematherr facilityis present,theerrormessagewill befairly informative. For example, theerrormessage

ode: range error (overflow) in lgamma while calculating y’

could be generatedif the logarithmic gammafunction ‘ lgamma ’ is evaluatedat a value of itsargumentthat is too large. Thegenerationof any suchmessage,excepta messagewarningof anunderflow, will causethenumericalsolutionto beinterrupted.

Thereis anothersort of error that may occurduring numericalsolution: the conditionthat anerrorceiling,which theusermaysetwith the‘ -r ’ optionor the‘ -e ’ option,is exceeded.This toowill causethenumericalsolutionto beabandoned,andode to switchbackto readinginput.

8.6 Numericalerror andhow to avoid it

This discussionis necessarilyincomplete.Entirebooksexist on any subjectmentionedbelow(e.g., floating point error). Our goalsare modest: first, to introducethe basicnotionsof erroranalysisasthey apply to ode ; second,to steeryou aroundthemoreobvious pitfalls. You should

Page 81: plotutils

Chapter8: Theode Program 76

look throughanumericalanalysistext (e.g.,Atkinson’s Introductionto NumericalAnalysis) beforebeginningthisdiscussion.

We begin with somekey definitions. The error of greatestconcernis the differencebetweentheactualsolutionandthenumericalapproximationto thesolution;this is termedtheaccumulatederror, sincetheerroris built upduringeachnumericalstep.Unfortunately, anestimateof thiserroris usuallynotavailablewithoutknowledgeof theactualsolution.Thereare,however, severalmoreusablenotionsof error. The single-steperror, in particular, is the differencebetweenthe actualsolutionandthenumericalapproximationto thesolutionafterany singlestep,assumingthevalueat thebeginningof thestepis correct.

Therelativesingle-steperror is thesingle-steperror, dividedby thecurrentvalueof thenumericalapproximationto the solution. Why not divided by the currentvalueof the solution itself? Thereasonis thatthesolutionis not exactly known. Whenfreeto choosea stepsize,ode will do soonthebasisof the relative single-steperror. By default, it will choosethestepsizeso asto maintainanaccuracy of eightsignificantdigits in eachstep. That is, it will choosethestepsizesoasnot toviolateanupperboundof 10́Lµ on therelative single-steperror. This ceiling maybeadjustedwiththe‘ -r ’ option.

Wheredoesnumericalerrorcomefrom? Therearetwosources.Thefirst is thefiniteprecisionofmachinecomputation.All computerswork with floatingpointnumbers,whicharenotrealnumbers,but only anapproximationto realnumbers.However, all computationsperformedby ode aredoneto doubleprecision,sofloatingpointerrortendsto berelatively small. You maynonethelessdetectthedifferencebetweenrealnumbersandfloatingpointnumbersby experimentingwith the‘ -p 17 ’option,which will print seventeensignificantdigits. On mostmachines,that is theprecisionof adoubleprecisionfloatingpointnumber.

The secondsourceof numericalerror is often calledthe theoretical truncationerror. It is thedifferencebetweenthe actualsolution and the approximatesolution duesolely to the numericalscheme. At the root of many numericalschemesis an infinite series;for ordinary differentialequations,it is a Taylor expansion.Sincethecomputercannotcomputeall thetermsin aninfiniteseries,anumericalschemenecessarilyusesatruncatedseries;hencetheterm. Thesingle-steperroris the sum of the theoreticaltruncationerror and the floating point error, thoughin practicethefloatingpoint erroris seldomincluded.Thesingle-steperrorestimatedby ode consistsonly of thetheoreticaltruncationerror.

We saythat a numericalschemeis stable, whenappliedto a particularinitial valueproblem,if the error accumulatedduring the solutionof the problemover a fixed interval decreasesasthestepsizedecreases;at least, over a wide rangeof stepsizes. With this definition both theRunge–Kutta–Fehlberg (‘ -R ’) schemeandtheAdams–Moulton(‘ -A ’) schemearestable(a statementbasedmoreonexperiencethanon theoreticalresults)for awideclassof problems.

After theseintroductory remarks,we list somecommonsourcesof accumulatederror andinstability in any numericalscheme.Usually, problemswith largeaccumulatederrorandinstabilityaredueto thesingle-steperrorin thevicinity of a ‘bad’ point beinglarge.

1. Singularities.

ode shouldnotbeusedtogenerateanumericalsolutiononany interval containingasingularity.Thatis,ode shouldnotbeaskedtostepoverpointsatwhichthesystemof differentialequationsis singularor undefined.

You will find the definitionsof singularpoint, regular singularpoint, and irregular singularpoint in any gooddifferentialequationstext. If you have no favorite, try Birkhoff andRota’s

Page 82: plotutils

Chapter8: Theode Program 77

OrdinaryDifferentialEquations, Chapter9. Alwayslocateandclassifythesingularitiesof asystem,if any, beforeapplyingode .

2. Ill-posedproblems.

For ode to yield an accuratenumericalsolution on an interval, the true solution must bedefinedandwell-behaved on that interval. Thesolutionmustalsobereal. Whenever any oftheseconditionsis violated,theproblemis saidto be ill-posed. Ill-posednessmayoccurevenif the systemof differentialequationsis well-behaved on the interval. Strangeresults,e.g.,thestepsizesuddenlyshrinkingto themachinelimit or thesolutionsuddenlyblowing up, mayindicateill-posedness.

As anexampleof ill-posedness(in fact,anundefinedsolution)considerthe innocent-lookingproblem:¶I·

=

¶I¸¶(1) = ¹ 1

Thesolutionon thedomainºx» 0 is¶( º ) = ¹ 1¼�º .

With this problemyou mustnot computea numericalsolutionon any interval that includesº = 0. To convinceyourselfof this, try to usethe‘step ’ statement

step 1, -1

on thissystem.How doesode react?

As anotherexampleof ill-posedness,considerthesystem¶ ·= 1¼

¶which is undefinedat

¶= 0. Thegeneralsolutionis¶

= ½ (2(º¾¹£¿ )) À�Á¸,

sothatif thecondition

¶(2) = 2 is imposed,thesolutionwill be(2º ) À�Á

¸. Clearly, if thedomain

specifiedin a ‘step ’ statementincludesnegative valuesof º , the generatedsolutionwill bebogus.

In general,whenusinga constantstepsizeyou shouldbecarefulnot to ‘stepover’ badpointsor badregions.Whenallowedto chooseastepsizeadaptively, ode will oftenspotbadpoints,but notalways.

3. Critical points.

An autonomoussystemis onethatdoesnot includetheindependentvariableexplicitly on theright-handsideof any differentialequation. A critical point for sucha systemis a point atwhichall right-handsidesequalzero.For example,thesystem¶ ·

= 2·

= 2

¶hasonly onecritical point,at ( Â�Ã

¶) = (0 Ã 0).

A critical point is sometimesreferredto asa stagnationpoint. That is becausea systemat acritical pointwill remainthereforever, thoughasystemnearacritical pointmayundergomoreviolentmotion. Undersomecircumstances,passingnearacritical pointmaygiveriseto alargeaccumulatederror.

As anexercise,solve thesystemabove usingode , with the initial condition  (0) =

¶(0) = 0.

Thesolutionshouldbeconstantin time. Now do thesamewith pointsnearthecritical point.Whathappens?

Page 83: plotutils

Chapter8: Theode Program 78

You shouldalways locate the critical points of a systembeforeattemptinga solution withode . Critical points may be classified(as equilibrium, vortex, unstable,stable,etc.) andthis classificationmaybeof use. To find out moreaboutthis, consultany bookdealingwiththequalitative theoryof differentialequations(e.g.,Birkhoff andRota’s OrdinaryDifferentialEquations, Chapter6).

4. Unsuitablenumericalschemes

If theresultsproducedby ode arebadin thesensethatinstabilityappearsto bepresent,or anunusuallysmallstepsizeneedsto bechosenneededin orderto reducethesingle-steperror tomanageablelevels,it maysimply bethatthenumericalschemebeingusedis not suitedto theproblem.For example, ode currentlyhasnonumericalschemewhichhandlesso-called‘stiff ’problemsvery well.

As anexample,youmaywish to examinethestiff problem:ÄIÅ = Æ 100 + 100Ç + 1Ä (0) = 1

on thedomain[0 È 1]. TheexactsolutionisÄ ( Ç ) = É�ÊÌËÎÍ�Í�Ï + Ç .It isausefulexercisetosolvethisproblemwith ode usingvariousnumericalschemes,stepsizes,andrelativesingle-steperrorbounds,andcomparethegeneratedsolutioncurveswith theactualsolution.

Thereareseveral roughandreadyheuristicchecksyou may performon the accuracy of anynumericalsolutionproducedby ode . Wediscussthemin turn.

1. Examinethestabilityof solutioncurves: do they converge?

That is, checkhow changingthestepsizeaffectsa solutioncurve. As thestepsizedecreases,thecurveshouldconverge. If it doesnot,thenthestepsizeis notsmallenoughor thenumericalschemeis not suitedto theproblem.In practice,youwouldproceedasfollows.Ð If usingan adaptive stepsize,superimposethe solution curves for successively smaller

boundson the relative single-steperror (obtainedwith, e.g., ‘ -r 1e-9 ’, ‘ -r 1e-11 ’,‘ -r 1e-13 ’, . . . ). If thecurvesconverge thenthesolutionis to all appearancesstable,andyouraccuracy is sufficient.Ð If employing a constantstepsize,performa similar analysisby successively halving thestepsize.

Thefollowing exampleis onethatyoumaywishto experimentwith. Makeafile named‘qcd ’containing:

# an equation arising in QCD (quantum chromodynamics )f’ = fpfp’ = -f*gˆ2g’ = gpgp’ = g*fˆ2f = 0; fp = -1; g = 1; gp = -1

print t, fstep 0, 5

Next make afile named‘stability ’, containingthelines:

Page 84: plotutils

Chapter8: Theode Program 79

: sserr is the bound on the relative single-step errorfor sserrdoode -r $sserr < qcddone | spline -n 500 | graph -T X -C

This is a ‘shell script’, which whenrun will superimposenumericalsolutionswith specifiedboundson therelative single-steperror. To run it, type:

sh stability 1 .1 .01 .001

anda plot of the solutionswith the specifiederror boundswill be drawn. The convergence,showing stability, shouldbequiteilluminating.

2. Checkinvariantsof thesystem:arethey constant?

Many systemshave invariantquantities.For example,if thesystemis a mathematicalmodelof a ‘conservative’ physicalsystemthenthe ‘energy’ (a particularfunction of the dependentvariablesof thesystem)shouldbeconstantin time. In general,knowledgeaboutthequalitativebehavior of any dependentvariablemaybeusedto checkthequalityof thesolution.

3. Checka family of solutioncurves: do they diverge?

A roughideaof how errorispropagatedisobtainedbyviewingafamilyof solutioncurvesaboutthenumericalsolutionin question,obtainedby varying the initial conditions. If they divergesharply—thatis, if two solutionswhichstartoutveryclosenonethelessendupfarapart—thenthequalityof thenumericalsolutionis dubious.On theotherhand,if thecurvesdonotdivergesharplythenany error that is presentwill in all likelihoodnot increaseby morethananorderof magnitudeor soover theinterval. Problemsexhibiting no sharpdivergenceof neighboringsolutioncurvesaresometimescalledwell-conditioned.

8.7 Runningtime

The time requiredfor ode to solve numericallya systemof ordinary differential equationsdependsonagreatmany factors.A few of themare:numberof equations,complexity of equations(numberof operatorsandnatureof theoperators),andnumberof stepstaken (avery complicatedfunction of thedifficulty of solution,unlessconstantstepsizesareused). Themosteffective wayto gaugethe time requiredfor solution of a systemis to clock a short or impreciserun of theproblem,andreasonasfollows: thetimerequiredto taketwo stepsis roughlytwicethatrequiredforone;andthereis a relationshipbetweenthenumberof stepsrequiredandtherelative errorceilingchosen.That relationshipdependson thenumericalschemebeingused,thedifficulty of solution,andperhapson the magnitudeof the error ceiling itself. A few carefully plannedshortrunsmaybe usedto determinethis relationship,enablinga long but impreciserun to be usedasan aid inprojectingthe costof a morepreciserun over the sameregion. Lastly, if a greatdealof dataisprinted,it is likely thatmoretime is spentin printing the resultsthanin computingthenumericalsolution.

8.8 The ode input languageformally specified

Thefollowing isaformalspecificationof thegrammarfor ode ’sinputlanguage,in Backus–Naurform. Nonterminalsymbolsin thegrammarareenclosedin anglebrackets. Terminaltokensareinall capitals.Barewordsandsymbolsstandfor themselves.

Page 85: plotutils

Chapter8: Theode Program 80

<program> ::= ... empty ...| <program> <statement>

<statement> ::= SEP| IDENTIFIER = <const> SEP| IDENTIFIER ’ = <expression> SEP| print <printlist> <optevery> <optfrom> SEP| step <const> , <const> , <const> SEP| step <const> , <const> SEP| examine IDENTIFIER SEP

<printlist> ::= <printitem>| <printlist> , <printitem>

<printitem> ::= IDENTIFIER| IDENTIFIER ’| IDENTIFIER ?| IDENTIFIER !| IDENTIFIER ˜

<optevery> ::= ... empty ...| every <const>

<optfrom> ::= ... empty ...| from <const>

<const> ::= <expression>

<expression> ::= ( <expression> )| <expression> + <expression>| <expression> - <expression>| <expression> * <expression>| <expression> / <expression>| <expression> ˆ <expression>| FUNCTION ( <expression> )| - <expression>| NUMBER| IDENTIFIER

Sincethisgrammarisambiguous,thefollowing tablesummarizestheprecedencesandassociativitiesof operatorswithin expressions.Precedencesdecreasefrom top to bottom.

Class Operators Associativity

Exponential ˆ rightMultiplicative * / leftAdditive + - left

Page 86: plotutils

Chapter8: Theode Program 81

As notedin thegrammar, therearesix typesof nontrivial statement.Wenow explain theeffects(the‘semantics’)of eachtype,in turn.

1. IDENTIFIER ’ = <expression>

Thisdefinesafirst-orderdifferentialequation.Thederivative of IDENTIFIER is specifiedby<expression> . If adynamicvariabledoesnotappearon theleft sideof astatementof thisform, its derivative is assumedto bezero.Thatis, it is asymbolicconstant.

2. IDENTIFIER = <const>

This setsthe value of IDENTIFIER to the currentvalue of <expression> . Dynamicvariablesthathave notbeeninitialized in thiswayaresetto zero.

3. step <const> , <const>

4. step <const> , <const> , <const>

A ‘step ’ statementcausesthenumericalschemeto be executed.Thefirst <const> is theinitial valueof theindependentvariable.Thesecondis its final value.Thethird is astepsize;ifgiven,it overridesany stepsizethatmaybespecifiedonthecommandline. Usuallythestepsizeis not specified,andit variesadaptively asthecomputationproceeds.

5. print <printlist> [ every <const> ] [ from <const> ]

A ‘print ’ statement controls the content and frequency of the numerical output.<printlist> is a comma-separatedlist of IDENTIFIER s, where each IDENTIFIERmaybefollowedby ‘ ’ ’, denotingthederivative,or ‘?’, denotingtherelative single-steperror,or ‘ ! ’, denotingthe absolutesingle-steperror, or ‘ ˜ ’, denotingthe accumulatederror (notcurrently implemented).The specifiedvaluesareprinted in the order they are found. Boththe ‘every ’ clauseandthe ‘ from ’ clauseareoptional. If the ‘every ’ clauseis present,aprinting occursevery <const> iterationsof thenumericalalgorithm. Thedefault is to printon every iteration(i.e. ‘every 1’). Thefirst andlastvaluesarealwaysprinted. If the‘ from ’clauseis present,it meansto begin printing whentheindependentvariablereachesor exceeds<const> . Thedefault is to begin printing immediately.

If no ‘print ’ statementhasbeensupplied,thenthe independentvariableandall dependentvariableswhichhave differentialequationsassociatedwith themareprinted.Theindependentvariableis printedfirst; thedependentvariablesfollow in theordertheirequationsweregiven.

6. examine IDENTIFIER

An ‘examine ’ statement,whenexecuted,causesa tableof interestinginformationaboutthenamedvariableto beprintedon thestandardoutput.For example,if thestatement‘examiney ’ wereencounteredafter executionof the ‘ode to Euler’ examplediscussedelsewhere,theoutputwouldbe:

"y" is a dynamic variablevalue:2.718282prime:2.718282sserr:1.121662e -0 9aberr:3.245638e -0 9acerr:0

code: push "y"

Thephrase‘dynamicvariable’meansthatthereisadifferentialequationdescribingthebehaviorof y . Thenumericitemsin thetableare:

value Currentvalueof thevariable.

Page 87: plotutils

Chapter8: Theode Program 82

prime Currentderivative of thevariable.

sserr Relative single-steperrorfor thelaststeptaken.

aberr Absolutesingle-steperrorfor thelaststeptaken.

acerr Total erroraccumulatedduringthemostrecent‘step ’ statement.Not currentlyimplemented.

The ‘code ’ sectionof the tablelists the stackoperationsrequiredto computethe derivativeof y (somewhat reminiscentof a reversePolishcalculator). This informationmay be usefulin discoveringwhethertheprecedencesin thedifferentialequationstatementwereinterpretedcorrectly, or in determiningthetimeor spaceexpenseof aparticularcalculation.‘push "y" ’meansto loady ’s valueon thestack,which is all that is requiredto computeits derivative inthiscase.

The grammarfor the ode input languagecontainsfour typesof terminaltoken: FUNCTION,IDENTIFIER , NUMBER, andSEP. They have thefollowing meanings.

1. FUNCTION

Oneof thewords:abs , sqrt , exp , log , ln , log10 , sin , cos , tan , asin , acos , atan ,sinh , cosh , tanh , asinh , acosh , atanh , floor , ceil , besj0 , besj1 , besy0 ,besy1 , erf , erfc , inverf , lgamma, gamma, norm , invnorm , ibeta , igamma. Thesearedefinedto have thesamemeaningasin theplottingprogramgnuplot . All functionstakea singleargument,exceptfor ibeta , which takesthree,andigamma, which takestwo. Fortrigonometricfunctions,all argumentsareexpressedin radians.Theatan functionis definedto give avaluebetweenÑ PI/2andPI/2 (inclusive).

2. IDENTIFIER

A sequenceof alphanumericcharactersstartingwith an alphabeticcharacter. The first 32charactersaresignificant. Upperandlower-caselettersaredistinct. In identifiers,theunder-scorecharacteris consideredalphabetic.Functionnamesandkeywordsmay not be usedasidentifiers,normay‘PI ’.

3. NUMBER

A non-emptysequenceof digits possiblycontaininga decimalpoint andpossiblyfollowedby an exponent. An exponentis ‘e’ or ‘E’, followed by an (optionally signed)one,two, orthree-digitnumber. All numbersandall partsof numbersareradix 10. A numbermay notcontainany white space.Thespecialword ‘PI ’ is anumber.

4. SEP

A separator:asemicolonor a (non-escaped)newline.

In theode input language,upperandlower-caselettersaredistinct. Commentsbegin with thecharacter‘#’ andcontinueto theendof the line. Long linesmaybecontinuedontoa secondlineby endingthefirst line with a backslash(‘ \ ’). That is becausethecombinationbackslash-newlineis equivalentto aspace.

Spacesor tabsarerequiredin theinputwheneverthey areneededtoseparateidentifiers,numbers,andkeywordsfrom oneanother. Exceptasseparators,they areignored.

Page 88: plotutils

Chapter8: Theode Program 83

8.9 Bibliography on ode andsolving differentialequations

K. E. Atkinson, An Introductionto NumericalAnalysis, Wiley, 1978. Chapter6 containsadiscussionof theliteratureon thenumericalsolutionof ordinarydifferentialequations.

G. Birkhoff andG. Rota,OrdinaryDifferentialEquations, 4thed.,Wiley, 1989.

N. B. Tufillaro, T. Abbott, andJ. Reilly, An ExperimentalApproachto NonlinearDynamicsandChaos, Addison–Wesley, 1992.AppendixC discussesanearlierversionof ode .

N. B. Tufillaro, E. F. Redish,and J. S. Risley, “ode : A numericalsimulationof ordinarydifferentialequations,” pp.480–481in Proceedingsof theConferenceonComputersin PhysicsInstruction, Addison–Wesley, 1990.

Page 89: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 84

9 libplot, a 2-D Vector Graphics Library

9.1 Programmingwith libplot : An overview

GNU libplot 4.1 is a free function library for drawing two-dimensionalvector graphics.It can producesmooth,double-buffered animationsfor the X Window System,and can exportgraphicsfiles in many file formats. It is ‘device-independent’ in thesensethat its API (applicationprogramminginterface)is to a large extent independentof the displaytype or outputfile format.TheAPI is thread-safe,soit maybeusedin multithreadedprograms.

Therearebindingsfor C,C++, andotherlanguages.TheC binding, whichis themostfrequentlyused,is alsocalled libplot , andthe C++ binding,whenit needsto be distinguished,is calledlibplotter . In thissectionweuselibplot to referto thelibrary itself, irrespectiveof binding.

Thegraphicalobjectsthatlibplot candraw includepaths,‘adjustedlabels’(i.e., justifiedtextstrings),markersymbols,andpoints(i.e.,pixels). Pathsmaybesimpleor compound.A simplepathis acontiguoussequenceof linesegments,circulararcs,elliptic arcs,quadraticBeziercurves,and/orcubic Beziercurves. A simplepathmay alsobe a circle, an ellipse,or a rectangle.A compoundpathconsistsof oneor morenestedsimplepaths. User-specifiedfilling of paths,bothsimpleandcompound,is supported(fill color andfill rule,aswell aspencolor, maybespecified).

Thereis supportfor maintaininga Postscript-stylestackof graphicscontexts, i.e., astackofdrawing attributesets.Path-relatedattributesincludepencolor, line thickness,line type,captype,join type,miterlimit, fill color, fill rule,andtransformationmatrix,andtext-relatedattributesincludefont name,font size,text angle,andtransformationmatrix.

The fundamentalabstractionprovidedby libplot is thatof a Plotter. A Plotteris anobjectwith an interfacefor the drawing of vectorgraphicswhich is similar to the interfaceprovided bya traditionalpenplotter. Therearemany typesof Plotter, which differ in the output format theyproduce. Any numberof Plotters,of the sameor different types,may exist simultaneouslyin anapplication.

Thedrawing operationssupportedby Plottersof differenttypesareidentical,in agreementwiththeprincipleof device independence.Soa graphicsapplicationthat is linkedwith libplot mayeasilybewritten soasto produceoutputin any or all of thesupportedoutputformats.

Thefollowing arethecurrentlysupportedtypesof Plotter.Ò X Plotters. An X Plotter, whenopened,popsup a window on an X Window Systemdisplayanddraws graphicsin it. The window will be ‘spunoff’ when the Plotter is closed;if it issubsequentlyreopened,a new window will bepoppedup. A spun-off window will remainonthescreenbut will vanishif you type‘q’ or click yourmousein it. FuturereleasesmaypermitX Plotters, whenreopened,to reuseanexisting window.Ò X DrawablePlotters.An X DrawablePlotterdrawsgraphicsin oneor two specifieddrawablesassociatedwith anX Window Systemdisplay. A ‘drawable’ is eithera window or a pixmap.ThedrawablesmustbepassedtothePlotterasparameters. (SeeSection9.5[PlotterParameters],page127.)Ò PNG Plotters. A PNG Plotterproducesa singlepageof output in PNG (PortableNetworkGraphics)format, and directsit to a file or other specifiedoutputstream. The file may beviewedor editedwith many applications,suchasthefreeimagedisplayapplicationxv andthefreeImageMagick package.

Page 90: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 85

Ó PNM Plotters.A PNM Plotterproducesa singlepageof outputin “portableanymap” format,and directs it to a file or other specifiedoutput stream. Thereare threetypesof portableanymap: PBM (portablebitmap, for monochromegraphics),PGM (portablegraymap),andPPM (portablepixmap, for coloredgraphics). The outputfile will be in whichever of thesethreeformatsis mostappropriate.Thefile maybeviewed or editedwith many applications,suchasxv andtheImageMagick package.Ó GIFPlotters.A GIFPlotterproducesasinglepageof output in apseudo-GIFformat. UnliketrueGIFformat,thepseudo-GIFformatdoesnotuseLZW compression: it usesrun-lengthencodinginstead.Soit doesnot transgresstheUnisyspatentthatrestrictstheuseof LZW compression.However, the outputfile may be viewed or editedwith any applicationthat understandsGIFformat,suchasxv andthe ImageMagick package.Thecreationof animatedpseudo-GIFsis supported.Ó SVG Plotters.An SVG Plotterproducesa singlepageof outputin ScalableVectorGraphicsformat and directsit to a file or other specifiedoutput stream. SVG is a new XML-basedformat for vector graphicson the Web, which is beingdevelopedby the GraphicsActivity(http://www.w3.o rg/ Graphi cs ) of the W3 Consortium(http://www.w3.or g).Theoutputconformsto the3 March2000versionof theSVG specification.Ó IllustratorPlotters.An IllustratorPlotterproducesa singlepageof outputin the formatusedby AdobeIllustrator, anddirectsit to a file or otherspecifiedoutputstream.Thefile maybeeditedwith AdobeIllustrator(version5, andmorerecentversions),or otherapplications.Ó PostscriptPlotters. A PostscriptPlotterproducesPostscriptoutputanddirectsit to a file orotherspecifiedoutputstream.If only a singlepageof graphicsis drawn on thePlotterthenitsoutputis in EPS(encapsulatedPostscript)format,soit maybeincludedin anotherdocument.It mayalsobeeditedwith thefree idraw drawing editor. SeeSectionE.1 [idraw], page160.Ó CGM Plotters. A CGM Plotterproducesoutput in ComputerGraphicsMetafile format anddirects it to a file or other specifiedoutput stream. By default, binary-encodedversion3CGM format is used. The outputcomplieswith the WebCGMprofile for Web-basedvectorgraphics,soit maybedisplayedin any Webbrowserwith WebCGMsupport.TheCGM OpenConsortium(http://www.cgmop en.o rg ) hasmoreinformationonWebCGM.Ó Fig Plotters.A Fig Plotterproducesasinglepageof outputin Fig formatanddirectsit to afileor otherspecifiedoutputstream.Theoutputmaybeeditedwith thefreexfig drawing editor.Thexfig editorcanexportdrawingsin variousotherformatsfor inclusionin documents.SeeSectionE.2 [xfig], page160.Ó PCL Plotters.A PCL Plotterproducesoutputin PCL 5 formatanddirectsit to a file or otherspecifiedoutputstream. PCL5 is a powerful versionof Hewlett–Packard’s PrinterControlLanguage,which supportsvectorgraphics.Theoutputmaybesentto a PCL5 device suchasaLaserJetprinteror high-endinkjet.Ó HP-GLPlotters.An HP-GLPlotterproducesoutputin theHewlett–PackardGraphicsLanguage(by default, in HP-GL/2),anddirectsit to a file or otherspecifiedoutputstream.Theoutputmaybeimportedinto anotherapplication,or sentto aplotter.Ó ReGISPlotters.A ReGISPlotterproducesoutputin ReGIS(remotegraphicsinstructionset)format anddirectsit to a file or otherspecifiedoutputstream.The outputmay be displayedon any terminalor emulatorthatunderstandsReGISformat. This includesseveral terminalsfrom DEC(in particular, theVT340,VT330,VT241,andVT240terminals),anddxterm , theDECwindows terminalemulationprogram.

Page 91: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 86

Ô TektronixPlotters.A TektronixPlotterproducesoutputin Tektronix4014formatanddirectsitto a file or otherspecifiedoutputstream.Theoutputmaybedisplayedon any Tektronix4014emulator. Suchan emulatoris built into xterm , the X Window Systemterminalemulationprogram.TheMS-DOSversionof kermit alsoincludessuchanemulator.Ô Metafile Plotters. A Metafile Plotterproducesoutput in GNU graphicsmetafileformat anddirects it to a file or other specifiedoutput stream. This format is an extendedversionofthe ‘plot(5)’ format found on someotheroperatingsystems. (SeeAppendixD [Metafiles],page158.) It may be translatedto other formats by an invocation of GNU plot . (SeeChapter3 [plot], page27.)

A distinctionamongthesetypesof Plotter is that all exceptX andX DrawablePlotterswritegraphicsto afile or otheroutputstream.An X Plotterpopsupits own windows,andanX DrawablePlotterdraws graphicsin oneor two X drawables.

Anotherdistinctionis that thefirst five typesof Plotter(X, X Drawable, PNG,PNM, andGIF)producebitmapoutput,while the remainingtypesproduceoutputin a vectorgraphicsformat. Inbitmapoutputthestructureof thegraphicalobjectsis lost,but in avectorformatit is retained.

An additionaldistinction is that X, X Drawable, ReGIS,Tektronix and Metafile Plottersarereal-time.Thismeansthatthey draw graphicsor write to anoutputstreamasthedrawing operationsareinvoked on them. The remainingtypesof Plotterarenot real-time,sincetheir outputstreamscanonly beemittedafterall functionshave beencalled.For PNM andGIF Plotters,this is becausethebitmapmustbeconstructedbeforeit is written out. For IllustratorandPostscriptPlotters,it isbecausea ‘boundingbox’ line mustbeplacedat theheadof theoutputfile. For a Fig Plotter, it isbecausecolor definitionsmustbeplacedat theheadof theoutputfile.

The most important operationssupportedby any Plotter are openpl and closepl ,which open and closeit. Graphicsmay be drawn, and drawing attributes set, only within anopenpl . . .closepl pair. The graphicsproducedwithin each openpl . . .closepl pairconstitutea ‘page’. In principle, any Plotter may be openedand closedarbitrarily many times.An X Plotter displays each page in a separateX window, and Postscript,PCL, and HP-GLPlottersrendereachpageasa separatephysicalpage.X Drawable, ReGISandTektronixPlottersmanipulatea single drawable or display, on which pagesare displayedin succession.Plottersthat do not draw in real time (PNG, PNM, GIF, Illustrator, Postscript,CGM, Fig, PCL, andHP-GL Plotters)maywait until their existencecomesto anend(i.e., until they aredeleted)beforeoutputtingtheirpagesof graphics.

In thecurrentreleaseof libplot , PostscriptandCGMPlottersdelayoutputtinggraphicsin thisway, but PCL andHP-GL Plottersoutputeachpageof graphicsindividually, i.e.,whencloseplis invoked. PNG,PNM, GIF, SVG, IllustratorandFig Plottersaresimilar, but outputonly thefirstpage.Thatis becausePNG,PNM, GIF, SVG, IllustratorandFig formatssupportonly asinglepageof graphics.

Thegraphicsdisplay, or‘viewport’, thatisdrawn in byaPlotterisnormallyasquareorrectangularregion on its outputdevice. But whenusingany Plotterto draw graphics,auserwill specifythecoordinatesof graphicalobjectsin device-independent ‘user’ coordinates,not in devicecoordinates.A Plottertransformsusercoordinatesto devicecoordinatesby performinganaffine transformation.

After invoking openpl to openaPlotter, anapplicationwouldusuallyinvoke space . spacespecifiesa rectangular‘window’ in the usercoordinatesystemthat will be mappedaffinely tothe viewport on the outputdevice. (The default window is a square,with oppositecorners(0,0)and(1,1).) The transformationfrom usercoordinatesto device coordinatesmay be updatedat

Page 92: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 87

any later time by reinvoking space , or by invoking fconcat . The fconcat operationwillconcatenate(i.e.,compose)thecurrentaffinetransformationwith anyspecifiedaffinetransformation.Thissortof concatenationis acapabilityfamiliar from, e.g.,Postscript.

EachPlottermaintainsa Postscript-stylestackof graphicscontexts. This makespossibletherapid,efficient drawing of complicatedpagesof graphics.A graphicscontext includesthecurrentaffine transformationfrom usercoordinatesto device coordinates. It also includessuchmodaldrawing attributesasgraphicscursorposition,pencolor, line type,line thickness,fill color, andthefont usedfor drawing text. The stateof any uncompletedpath(if any) is includedaswell, sincepathsmaybedrawn incrementally, oneportion(line segment,arc,or Beziercurve) ata time.

Warning: Much as in Postscript,the currentgraphicscontext may be pushedonto the stackby calling savestate , and poppedoff by calling restorestate . However, libplot ’sandPostscript’s drawing modelsaresignificantlydifferent. In libplot , the new graphicscon-text createdby savestate containsno path. So a new path may be constructedin it fromscratch,anddrawn. Afterwards,thepathin the formergraphicscontext will be returnedto whenrestorestate is called, at which time it may be extendedfurther. Another differencefromPostscriptis thatin libplot , thereis noneedto startanew pathby callinga‘newpath ’ function.Instead,you just startdrawing. At leastin theory, you do needto enda pathexplicitly, by callingendpath to requestthatit bedrawn on thegraphicsdisplay. But thecall to endpath canusuallybeomitted.Forexample,callingrestorestate automaticallyinvokesendpath to endthepath(if any) containedin thecurrentgraphicscontext.

To permitvectorgraphicsanimation,any pageof graphicsmaybesplit into ‘frames’. A frameis ended,anda new frameis begun, by invoking the erase operation. This first terminatesthepathunderconstruction,if any. What thenhappensdependson whetherthePlotterdoesreal-timeplotting. If it does(i.e., if thePlotteris anX, X Drawable, ReGIS,Tektronix,or MetafilePlotter),erase removesall plottedobjectsfrom the graphicsdisplay, allowing a new frameto bedrawn.Displayingasequenceof framesin successioncreatestheillusion of smoothanimation.

OnmostPlottersthatdo notdo real-timeplotting (i.e.,PNG,PNM, SVG, Illustrator, Postscript,CGM, Fig, PCL, or HP-GL Plotters),invoking erase deletesall plottedobjectsfrom aninternalbuffer. For this reason,mostPlottersthat do not do real-timeplotting will displayonly the finalframeof any multiframepage.

GIF Plottersarein a classby themselves. Eventhoughthey do not do real time plotting,a GIFPlottercanproducemulti-imageoutput,i.e.,ananimatedpseudo-GIFfile, from amultiframepage.As notedabove, thepseudo-GIFfile producedby a GIF Plotterwill containonly thefirst pageofgraphics.But if thispageconsistsof multiple frames,theneachinvocationof erase afterthefirstwill betreated,by default, asaseparatorbetweensuccessive images.

9.2 C Programmingwith libplot

9.2.1 The C applicationprogramminginterface

GNU libplot hasbindingsfor severalprogramminglanguages.Regardlessof whichbindingis used,theconceptsbehindlibplot (Plotters,andafixedsetof operationsthatmaybeappliedtoany Plotter)remainthesame.However, thewaysin whichPlottersaremanipulated(created,selectedfor use, anddeleted)maydiffer betweenbindings.ThissectiondiscussesthecurrentC binding. Forinformationon olderC bindings, seeSection9.2.2[OlderC APIs], page89.

Page 93: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 88

In the C binding, a Plotter is implementedasan opaquedatatype,plPlotter , which mustbe accessedthrough a pointer. Each drawing operationtakes a pointer to a plPlotter asits first argument. The functionspl_newpl_r andpl_deletepl_r are the constructoranddestructorfor theplPlotter datatype.Thefinal argumentof pl_newpl_r mustbeapointertoaplPlotterParams object,whichspecifiesPlotterparameters.pl_newpl_r returnsapointerto a plPlotter .

You shouldalwayscall pl_deletepl_r whenyou arefinishedusinga Plotter. In general,Plottersthat do not plot graphicsin real time (PostscriptPlottersandCGM Plottersin particular)write outgraphicsonly whenpl_deletepl_r is called.

Thefollowing tablessummarizetheactionof thePlottermanipulationfunctionsin theC binding.

plPlotter* pl_newpl_r (constchar* type, FILE * infile, FILE *outfile, FILE *errfile,plPlotterParams*params);

CreateaPlotterof typetype, wheretypemaybe" X" , " Xdrawable" , " png" , " pnm" ," gif" , " svg" , " ai" , " ps" , " cgm" , " fig" , " pcl" , " hpgl" , " regis" , " tek" , or " meta" .ThePlotterwill have inputstreaminfile, outputstreamoutfile, anderrorstreamerrfile.Any or all of thesethreemaybeNULL. Currently, all Plottersarewrite-only, soinfileis ignored.X PlottersandX DrawablePlotterswrite graphicsto anX Window Systemdisplayratherthanto anoutputstream,soif type is " X" or " Xdrawable" thenoutfileis ignoredaswell. Error messages(if any) are written to the streamerrfile, unlesserrfile is NULL.

All Plotterparameterswill becopiedfrom theplPlotterParam s objectpointedtoby params. A NULL returnvalueindicatesthePlottercouldnotbecreated.

int pl_deletepl_r (plPlotter*plotter);DeletethespecifiedPlotter. A negative returnvalueindicatesthePlottercouldnot bedeleted.

The functionspl_newplparams , pl_deleteplpara ms, andpl_copyplparams arethe constructor, destructor, and copy constructorfor the plPlotterParam s datatype. Thefunctionpl_setplparam setsany singlePlotterparameterin aplPlotterParams object.

plPlotterParams* pl_newplparams ();

int pl_deleteplpar ams (plPlotterParams*plotter params);

plPlotterParams* pl_copyplparams (constplPlotterParams*params);

int pl_setplparam (plPlotterParams*params, constchar*parameter, void *value);Setthevalueof theparameterparameterto value in theobjectpointedto by params.For mostparameters,valueshouldbea char * , i.e., a string. If value is NULL, theparameteris unset.

For a list of recognizedparametersandtheirmeaning,seeSection9.5 [PlotterParam-eters],page127. Unrecognizedparametersareignored.

Thereasonwhy theplPlotterParam s datatypeexistsis thateventhoughthePlotterinterfaceis largelyPlotter-independent, it is usefulto beableto specifycertainaspectsof aPlotter’sbehaviorat creationtime. If a a parameterhasbeenset in the specifiedplPlotterParam s object,thatwill be thevalueusedby thePlotter. If a parameteris not set,thePlotterwill usea default valuefor it, unlesstheparameteris string-valuedandthereis anenvironmentvariableof thesamename,in which casethe value of that environmentvariablewill be used. This rule increasesrun-time

Page 94: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 89

flexibility: anapplicationprogrammermayallow non-criticalPlotterparametersto bespecifiedbytheuservia environmentvariables.

In theC binding,eachdrawing operationthatmaybe invoked on a Plotteris representedby afunctionwhosenamebeginswith " pl " andendswith " r" . For example,theopenpl operationisinvokedonaPlotterby callingthefunctionpl_openpl_r , thefirst argumentof whichis apointerto thecorrespondingplPlotter object.

9.2.2 Older C applicationprogramminginterfaces

ThecurrentC API (applicationprogramminginterface),which is thread-safe,is a revisionof anolderAPI thatis not thread-safe.Thatis why mostfunctionsin thecurrentAPI havenamesthatendin " r" , whichstandsfor ‘revised’or ‘reentrant’.

In theold CAPI, thePlotteronwhichanoperationwasperformedisnotspecifiedasanargumentof thefunctionthatwascalledto performtheoperation.Instead,aPlotteris first ‘selected’.ThentheAPI functionis called.pl_openpl wasonesuchfunction; it opensthecurrentlyselectedPlotter,i.e.,beginsapageof graphics.

Theold API is deprecated,but is still supported.Thefour functionsin theold API thatperformPlottermanipulationhave thefollowing semantics.

int pl_newpl (constchar* type, FILE * infile, FILE *outfile, FILE *errfile);CreateaPlotterof typetype, wheretypemaybe" X" , " Xdrawable" , " png" , " pnm" ," gif" , " svg" , " ai" , " ps" , " fig" , " pcl" , " hpgl" , " regis" , " tek" , or " meta" . ThePlotterwill have inputstreaminfile, outputstreamoutfile, anderrorstreamerrfile. Thereturnvalueis a ‘handle’: anonnegative integerby which thenewly createdPlotterisreferredto. A negative returnvalueindicatesthePlottercouldnotbecreated.

int pl_selectpl (int handle);Selecta Plotter, referredto by its handle,for use. Only onePlottermay be selectedata time. A negative returnvalueindicatesthespecifiedPlottercouldnotbeselected.Otherwise,thereturnvalueis thehandleof thepreviously selectedPlotter.

At startup,a singleMetafilePlotterthatwritesto standardoutput(with handle‘0’ ) isautomaticallycreatedandselected.

int pl_deletepl (int handle);DeleteaPlotter, specifiedby its handle.ThePlottermustnotbeselectedat thetime itis deleted.A negative returnvalueindicatesthePlottercouldnotbedeleted.

int pl_parampl (constchar*parameter, void *value);Settheglobalvalueof thePlotterparameterparameterto value. Theparametervaluesin effect at thetimeany Plotteris createdwill becopiedinto it.

In theold API, selectinga Plotterwith pl_selectpl andsettinga valuefor a Plotterparameterwith pl_parampl areglobaloperations.Thatis why theold API is not thread-safe.

An evenolderC API omittedtheprefix" pl " fromthenamesof libplot functions.Theprefix" pl " wasaddedin parttodistinguishGNU libplot frompre-GNUversionsof libplot . If youneedto compilecodewrittenfor veryearlyversionsof GNU libplot or for pre-GNUlibplot ,you should include the headerfile plotcompat.h . plotcompat.h redefinesopenpl aspl_openpl , andsoforth. SeeSection9.2.3[C CompilingandLinking], page90.

Page 95: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 90

9.2.3 C compiling andlinking

Thesourcecodefor agraphicsapplicationwritten in C, if it is to usetheGNU libplot C API(C applicationprogramminginterface),mustcontainthelines

#include <stdio.h>#include <plot.h>

The headerfile ‘plot.h ’ is distributedwith libplot , andshouldhave beeninstalledon yoursystemwhereyour C compilerwill find it. It containsa prototypefor eachof the functionsin theC API, andsomemiscellaneousdefinitions.

ToeachPlotteroperationtherecorrespondsafunctionin theC API whosenamebeginswith " pl "andendswith " r" . To invoke thePlotteroperation,this functionwould be called. For example,theopenpl operationwould beinvoked on a Plotterby calling thefunctionpl_openpl_r , thefirst argumentof which is apointerto thePlotter. All suchfunctionsaredeclaredin ‘plot.h ’.

In releasesof GNU libplot before libplot 3.0, Plotteroperationswereperformedin adifferentway. For example,therewasa functionpl_openpl thatoperatedon a Plotterthatwas‘selected’,ratherthanspecifiedasanargument.Theold C API is still supportedby ‘plot.h ’. Formoreinformationon it, seeSection9.2.2[OlderC APIs], page89.

In evenolderreleasesof GNU libplot , andin thenon-GNUversionsof libplot thatpre-cededit, the" pl " prefixwasnotused.If youneedtocompilecodewrittenfor early versionsof GNUlibplot or for non-GNU libplot , you shouldalsoincludetheheaderfile plotcompat.h .Thatfile redefinesopenpl aspl_openpl , andsoforth.

To link yourapplicationwith GNU libplot , youwouldusetheappropriate‘ -l ’ option(s)onthecommandline whencompilingit. You woulduse

-lplot -lXaw -lXmu -lXt -lXext -lX11 -lpng -lz -lm

or, in recentreleasesof theX Window System,

-lplot -lXaw -lXmu -lXt -lSM -lICE -lXext -lX11 -lpng -lz -lm

Theselinking optionsassumethatyourversionof libplot hasbeencompiledwith PNGsupport;if not, youwouldomit the‘ -lpng -lz ’ options.

As analternative to thepreceding,youmayneedto use‘ -lplot -lXm -lXt -lXext -lX11-lpng -lz -lm ’, ‘ -lplot -lXm -lXt -lXext -lX11 -lpng -lz -lm -lc -lgen ’, or‘ -lplot -lXm -lXt -lXext -lX11 -lpng -lz -lm -lc -lPW ’, on systemsthat provideMotif widgetsinsteadof Athenawidgets. In recentreleasesof theX Window System,you wouldinsert‘ -lSM -lICE ’. Recentreleasesof Motif require‘ -lXp ’ andpossibly‘ -lXpm ’ aswell.)

On someplatforms,the directoriesin which libplot or the other librariesarestoredmustbespecifiedon thecommandline. For example, theoptions‘ -lXaw -lXmu -lXt -lSM -lICE-lXext -lX11 ’, whichspecifyX Window Systemlibraries,mayneedto beprecededby anoptionlike ‘ -L/usr/X11/lib ’.

On mostsystemslibplot is installedasa sharedlibrary. This meansthat the linking withyour applicationwill take placeat run time ratherthancompile time. The environmentvariableLD_LIBRARY_PATHlists thedirectorieswhich will besearchedfor sharedlibrariesat run time.For your applicationto be executable,this environmentvariableshouldinclude the directory inwhich libplot is stored.

Page 96: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 91

9.2.4 Sampledrawings in C

Thefollowing is a sampleapplication,written in C, that invokesGNU libplot operationstodraw vectorgraphics.It draws an intricateandbeautifulpath(Bill Gosper’s “C” curve, discussedas Item #135 in HAKMEM , MIT Artificial IntelligenceLaboratoryMemo #239,1972). As thenumericconstantMAXORDER(hereequalto 12) is increased,the pathwill take on the shapeof acurly letter“C”, which is theenvelopeof amyriadof epicyclic octagons.

#include <stdio.h>#include <plot.h>#define MAXORDER12

void draw_c_curve (plPlotter *plotter, double dx, double dy, int order){

if (order >= MAXORDER)/* continue path along (dx, dy) */pl_fcontrel_r (plotter, dx, dy);

else{

draw_c_curve (plotter,0.5 * (dx - dy), 0.5 * (dx + dy), order + 1);

draw_c_curve (plotter,0.5 * (dx + dy), 0.5 * (dy - dx), order + 1);

}}

int main (){

plPlotter *plotter;plPlotterParams *plotter_param s;

/* set a Plotter parameter */plotter_params = pl_newplparams ();pl_setplparam (plotter_param s, "PAGESIZE", "letter");

/* create a Postscript Plotter that writes to standard output */if ((plotter = pl_newpl_r ("ps", stdin, stdout, stderr,

plotter_params )) == NULL){

fprintf (stderr, "Couldn’t create Plotter\n");return 1;

}

if (pl_openpl_r (plotter) < 0) /* open Plotter */{

fprintf (stderr, "Couldn’t open Plotter\n");return 1;

}pl_fspace_r (plotter, 0.0, 0.0, 1000.0, 1000.0); /* set coor system */pl_flinewidth_r (plotter, 0.25); /* set line thickness */pl_pencolorname _r (plotter, "red"); /* use red pen */

Page 97: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 92

pl_erase_r (plotter); /* erase graphics display */pl_fmove_r (plotter, 600.0, 300.0); /* position the graphics cursor */draw_c_curve (plotter, 0.0, 400.0, 0);if (pl_closepl_r (plotter) < 0) /* close Plotter */

{fprintf (stderr, "Couldn’t close Plotter\n");return 1;

}

if (pl_deletepl_r (plotter) < 0) /* delete Plotter */{

fprintf (stderr, "Couldn’t delete Plotter\n");return 1;

}return 0;

}

As youcansee,thisapplicationbeginsby creatingaplPlotterParams objectto holdPlotterparameters,andsetsthePAGESIZEparameter. It thencallsthepl_newpl_r functionto createaPostscriptPlotter. ThePostscriptPlotterwill produceoutputfor aUS letter-sizedpage,thoughanyotherstandardpagesize,e.g.," a4" , couldbesubstituted.This would bearrangedby alteringthecall to pl_setplparam . ThePAGESIZEparameteris oneof severalPlotterparametersthatanapplicationprogrammermayset.For a list, seeSection9.5 [PlotterParameters],page127.

After the Plotteris created,the applicationopensit anddraws the “C” curve recursively. Thedrawing of the curve is accomplishedby calling the pl_fmove_r function to positionthe Plot-ter’s graphicscursor, and then calling draw_c_curve . This subroutinerepeatedlycalls pl_fcontrel_r . Thepl_fcontrel_r functioncontinuesa pathby addinga line segmentto it.Theendpointof eachline segmentis specifiedin relative floatingpoint coordinates,i.e., asa float-ing point offset from the previous cursorposition. After the “C” curve is drawn, the Plotter isclosedby callingpl_closepl_r ,whichautomaticallyinvokespl_endpath_r to endthepath.A Postscriptfile is writtento standardoutputwhenpl_deletepl_r is calledto deletethePlotter.

Specifying" png" , " pnm" , " gif" , " svg" , " ai" , " cgm" , " fig" , " pcl" , " hpgl" , " regis" , " tek" ,or " meta" asthefirst argumentin thecall to pl_newpl_r , insteadof " ps" , wouldyield aPlotterthat would write graphicsto standardoutput in the specifiedformat, insteadof Postscript. ThePAGESIZE parameteris relevant to the " svg" , " ai" , " cgm" , " fig" , " pcl" , and " hpgl" outputformats,but is ignoredfor theothers.Specifying" meta" asthePlottertypemaybeusefulif youwish to avoid recompilationfor differentoutputdevices.Graphicsmetafileoutputmaybepipedtotheplot utility andconvertedto any othersupportedoutputformat,or displayedin anX window.SeeChapter3 [plot], page27.

If " X" werespecifiedasthe first argumentof pl_newpl_r , the curve would be drawn in apopped-upX window, andtheoutputstreamargumentwouldbeignored.WhichX Window Systemdisplaythewindow would popup on would be determinedby theDISPLAY parameter, or if thatparameterwerenotset,by theDISPLAY environmentvariable.Thesizeof theX window wouldbedeterminedby theBITMAPSIZE parameter, or if thatparameterwerenotset,by theBITMAPSIZEenvironmentvariable.Thedefault valueis " 570x570" . For the" png" , " pnm" , and" gif" Plottertypes,theinterpretationof BITMAPSIZE is similar.

Youcouldalsospecify" Xdrawable" asthePlottertype. For you to make thiswork, youwouldneedto know a bit aboutX Window Systemprogramming.You would needto createat leastone

Page 98: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 93

X drawable(i.e., window or a pixmap),andby invoking pl_setplparam beforepl_newpl_r is called, set it as the value of the parameterXDRAWABLE_DRAWABLE1 or XDRAWABLE_DRAWABLE2. For theparametersthataffect X DrawablePlotters,seeSection9.5 [PlotterParame-ters],page127.

Thefollowing is anothersampleapplication,written in C, thatinvokeslibplot operationstodraw vectorgraphics. It draws a spiral consistingof elliptically boxed text strings,eachof whichreads" GNU libplot!" . Thisfigurewill besentto standardoutputin Postscriptformat.

#include <stdio.h>#include <plot.h>#include <math.h>#define SIZE 100.0 /* nominal size of user coordinate frame */#define EXPAND2.2 /* expansion factor for elliptical box */

void draw_boxed_str in g (plPlotter *plotter,char *s, double size, double angle)

{double true_size, width;

pl_ftextangle_r (plotter, angle); /* set text angle (degrees) */true_size = pl_ffontsize_r (plotter, size); /* set font size */width = pl_flabelwidth_r (plotter, s); /* compute width of string */pl_fellipserel_ r (plotter, 0.0, 0.0,

EXPAND* 0.5 * width, EXPAND* 0.5 * true_size,angle); /* draw surrounding ellipse */

pl_alabel_r (plotter, ’c’, ’c’, s); /* draw centered text string */}

int main(){

plPlotter *plotter;plPlotterParams *plotter_param s;int i;

/* set a Plotter parameter */plotter_params = pl_newplparams ();pl_setplparam (plotter_param s, "PAGESIZE", "letter");

/* create a Postscript Plotter that writes to standard output */if ((plotter = pl_newpl_r ("ps", stdin, stdout, stderr,

plotter_params )) == NULL){

fprintf (stderr, "Couldn’t create Plotter\n");return 1;

}

if (pl_openpl_r (plotter) < 0) /* open Plotter */{

fprintf (stderr, "Couldn’t open Plotter\n");return 1;

}

Page 99: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 94

/* specify user coor system */pl_fspace_r (plotter, -(SIZE), -(SIZE), SIZE, SIZE);pl_pencolorname _r (plotter, "blue"); /* use blue pen */pl_fillcolornam e_r (plotter, "white"); /* set white fill color */pl_filltype_r (plotter, 1); /* fill ellipses with fill color *//* choose a Postscript font */pl_fontname_r (plotter, "NewCenturySchl bk -Ro man" );

for (i = 80; i > 1; i--) /* loop through angles */{

double theta, radius;

theta = 0.5 * (double)i; /* theta is in radians */radius = SIZE / pow (theta, 0.35); /* this yields a spiral */pl_fmove_r (plotter, radius * cos (theta), radius * sin (theta));draw_boxed_stri ng (plotter, "GNU libplot!", 0.04 * radius,

(180.0 * theta / M_PI) - 90.0);}

if (pl_closepl_r (plotter) < 0) /* close Plotter */{

fprintf (stderr, "Couldn’t close Plotter\n");return 1;

}if (pl_deletepl_r (plotter) < 0) /* delete Plotter */

{fprintf (stderr, "Couldn’t delete Plotter\n");return 1;

}return 0;

}

Thisexampleshowswhatis involvedin plottingatext stringor text strings.First,thedesiredfontmustberetrieved. A font is fully specifiedby calling pl_fontname_r , pl_fontsize_r , andpl_textangle_r , or their floatingpoint counterpartspl_ffontname_r , pl_ffontsize_r , andpl_ftextangle_r . Sincethesethreefunctionsmaybecalledin any order, eachof themreturnsthesizeof thefont thatit selects,asaconveniencetotheprogrammer. Thismaydifferslightlyfrom thesizespecifiedin themostrecentcall to pl_fontsize_r or pl_ffontsize_r , sincemany Plottershave only a limited repertoryof fonts. Theabove exampleplots eachtext string inthe " NewCenturySchlbk-Roman" font, which is availableon PostscriptPlotters.SeeSectionA.1[Text Fonts],page134.

If you replace" ps" by " X" in thecall to pl_newpl_r , anX Plotterratherthana PostscriptPlotterwill beused,andthespiralwill bedrawn in apopped-upX window. If your X displaydoesnotsupportthe" NewCenturySchlbk-Roman" font, youmaysubstituteany otherscalablefont,suchasthewidely available" utopia-medium-r-normal" . For theformatof font names,seeSectionA.3[Text Fontsin X], page140. If theX Plotteris unableto retrieve the font you specify, it will firstattemptto usea default scalablefont (" Helvetica" ), andif that fails, usea default Hershey vectorfont (" HersheySerif" ) instead.Hershey fontsareconstructedfrom line segments,soeachbuilt-inHershey font is availableonall typesof Plotter.

Page 100: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 95

If you areusinganolder (pre-X11R6)X Window Systemdisplay, you will find that retrievinga scalablefont is a time-consumingoperation.Theabove examplemayrun slowly on someolderX displays, sinceanew font mustberetrievedbeforeeachtext stringis drawn. Thatis becauseeachtext string hasa differentangleof inclination. It is possibleto retrieve individual charactersfroman X11R6 display, ratherthanretrieving an entirerasterizedfont. If this featureis available, theX Plotterwill automaticallytake advantageof it to save time.

9.2.5 Simplepathsandcompoundpaths

Themostsophisticatedsortof graphicalobjectthatlibplot candraw is apath. In thissectionwe explain the fine detailsof constructingpaths. The other threesortsof graphicalobject (textstrings,marker symbols,andpoints[i.e., pixels]) arediscussedelsewhere.

As in Postscript,pathsmay be simpleor compound.A simplepathis a contiguoussequenceof line segments,circular arcs,elliptic arcs,quadraticBeziercurves,and/orcubic Beziercurves.A simplepathmay alsobe a circle, an ellipse,or a rectangle. A compoundpathconsistsof oneor moresimplepaths,which mustbe nested: they shouldnot intersecteachother. This is morerestrictivethanin Postscript.

libplot ’sdrawing modelis significantlydifferentfrom Postscript’s,andis moreuser-friendly.Before drawing a path by invoking libplot operations,you do not needto call any specialfunction. You would specifytheattributesof thepathbeforedrawing, however. Attributesincludepencolor, line type,line width, captype,join type,andmiter limit. If thepathis to befilled, thefillcolorandfill rulewouldbespecifiedtoo. All theseattributesare‘modal’: theirvaluesarepreservedfrom pathto path.

In principle,youwouldendany pathyouconstruct,andrequestthatit bedrawn on thegraphicsdisplay, by invoking the endpath operation. But endpath is called automaticallywhen anypath-relatedattribute is changed,whenmove is calledto changethegraphicscursorposition,andbeforeany otherobjectis constructedanddrawn. It isalsocalledattheendof eachpageof graphics,i.e., whenclosepl is invoked. So invoking endpath explicitly is usuallyunnecessary. This isquitedifferentfrom Postscript,whereanexplicit commandto stroke or fill apathis required.

libplot alsodiffers from Postscriptin theway it constructsanddraws compoundpaths. Inlibplot , youwouldendeachof theconstituentsimplepathsof acompoundpathby invoking theendsubpath operation.After all simplepathsaredrawn, thecompoundpathasa wholewouldbedrawn by invoking endpath . After eachof thecallsto endsubpath , you areallowedto callmove to repositionthegraphicscursor, prior to beginningthenext simplepath. Immediatelyafteraninvocationof endsubpath , acall to move will notautomaticallyinvoke endpath .

Thefollowing sampleprogramusesaPostscriptPlotterto producePostscriptoutput. It draws atypicalcompoundpath,whichconsistsof 17 simplepaths.Thefirst simplepathis a largebox. Thisbox contains7 circles, nestedwithin eachother, anda separatesetof 7 circlesthatarealsonestedwithin eachother. Within eachof thetwo setsof nestedcirclesis apairof contiguousline segments,which make up an additionalsimplepath. Thecompoundpathis drawn in green,andit is filled.Thefill color is light blue.

#include <stdio.h>#include <plot.h>

Page 101: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 96

int main (){

int i, j;plPlotter *plotter;plPlotterParams *plotter_param s;

/* set a Plotter parameter */plotter_params = pl_newplparams ();pl_setplparam (plotter_param s, "PAGESIZE", "letter");/* create a Postscript Plotter that writes to standard output */plotter = pl_newpl_r ("ps", stdin, stdout, stderr, plotter_params) ;/* open Plotter, i.e. begin a page of graphics */pl_openpl_r (plotter);

pl_fspace_r (plotter, 0.0, 0.0, 1000.0, 1000.0); /* set coor system */pl_flinewidth_r (plotter, 5.0); /* set line thickness */pl_pencolorname _r (plotter, "green");pl_fillcolornam e_r (plotter, "light blue");pl_filltype_r (plotter, 1); /* do filling, full strength */pl_erase_r (plotter); /* erase graphics display */

/* draw a compound path consisting of 17 simple paths */

/* draw the first simple path: a large box */pl_orientation_ r (plotter, 1);pl_fbox_r (plotter, 50.0, 50.0, 950.0, 950.0);pl_endsubpath_r (plotter);for (i = 0; i < 2; i++)

/* draw 8 simple paths that are nested inside the box */{

/* first, draw 7 simple paths: nested circles */for (j = 9; j >= 3; j--)

{pl_orientation_r (plotter, j % 2 ? -1 : 1);pl_fcircle_r (plotter, 250.0 + 500 * i, 500.0, j * 20.0);pl_endsubpath_r (plotter);

}/* draw an open simple path comprising two line segments */pl_fmove_r (plotter, 225.0 + 500 * i, 475.0);pl_fcont_r (plotter, 250.0 + 500 * i, 525.0);pl_fcont_r (plotter, 275.0 + 500 * i, 475.0);pl_endsubpath_r (plotter);

}/* formally end the compound path (not actually necessary) */pl_endpath_r (plotter);

/* close Plotter, i.e. end page of graphics */pl_closepl_r (plotter);

Page 102: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 97

/* delete Plotter */if (pl_deletepl_r (plotter) < 0)

{fprintf (stderr, "Couldn’t delete Plotter\n");return 1;

}return 0;

}

As youwill seeif yourunthisprogram,thefilling of thecompoundpathtakesplacein avisuallypleasingway: alternatingannularregionsarefilled. Thatis becauselibplot ’sdefault fill rule is" even-odd" . Sinceacompoundpath’sconstituentsimplepathsmustalwaysbenested,it is easyforlibplot to determinewhich regionsbetweenthemare‘even’ andwhichare‘odd’. It is thelatterthatarefilled.

The above programincludesmany invocationsof orientation . The value of the modal‘orientation’ attribute (1, meaningcounterclockwise,or Õ 1, meaningclockwise)appliesto subse-quentlydrawn boxes,circles,andellipses.If " even-odd" filling is used,they have noeffect. But ifthefill rulefor thecompoundpathis setto " nonzero-winding" by aninitial call to fillmod , thesecallsto orientation will arrangematterssothatalternatingannularregionsarefilled, just asif" even-odd" filling wereused.

If theprecedingparagraphis mysterious,it would bewiseto consulta goodbookon Postscriptprogramming,or any otherreferenceon thesubjectof ‘winding numbers’.

9.2.6 Drawing on a physical page

GNU libplot candraw graphicsoveranentirepageof paper, notmerelywithin thegraphicsdisplayor ‘viewport’ thatit normallyuses.

The default viewport usedby an Illustrator, Postscript,Fig, or PCL Plotter is a squareregioncenteredonthepage.Thesizeof thedefaultviewportdependsonthePAGESIZEparameter, whichmaybe " letter" , " a4" , etc. SeeAppendixC [PageandViewport Sizes],page156. For example,thedefault viewport on a letter-sizedpage,which haswidth 8.5in andheight11in, is a squareofside8 in.

However, youmayspecifydifferentdimensionsfor theviewport,andadifferentpositionaswell.In particular, you mayspecifya viewport thatcoverstheentirepage.This would beaccomplishedby settingPAGESIZE to, for example, " letter,xsize=8.5in,ysize=11in,xorigin=0in,yorigin=0in" ." xorigin" and" yorigin" specifythelocationof thelower left cornerof theviewport, relative to thelower left cornerof thepage.

With thischoicefor theviewport,theentirepageis in principleimageable.Forfull-pagedrawing,it is convenientto definea usercoordinatesystemin termsof which the lower left cornerof thepageis (0,0), andin which theunits arephysicalinchesor centimeters.To do so,you would useappropriateargumentswheninvoking thespace operationon thePlotter. Thefollowing programshows how thespace operationwouldbeinvoked.

#include <stdio.h>#include <plot.h>

Page 103: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 98

int main(){

plPlotter *plotter;plPlotterParams *plotter_param s;

/* set page size parameter, including viewport size and location */plotter_params = pl_newplparams ();pl_setplparam (plotter_param s, "PAGESIZE",

"letter,xsize=8 .5i n, ys iz e=11i n, xo ri gi n=0in ,y or ig in= 0i n" );

/* create a Postscript Plotter with the specified parameter */plotter = pl_newpl_r ("ps", stdin, stdout, stderr, plotter_params) ;

pl_openpl_r (plotter); /* begin page of graphics */pl_fspace_r (plotter,

0.0, 0.0, 8.5, 11.0); /* set user coor system */

pl_fontname_r (plotter, "Times-Bold");pl_ffontsize_r (plotter, 0.5); /* font size = 0.5in = 36pt */

pl_fmove_r (plotter, 1.0, 10.0);pl_alabel_r (plotter, ’l’, ’x’, "One inch below the top");pl_fline_r (plotter, 1.0, 10.0, 7.5, 10.0);

pl_fmove_r (plotter, 7.5, 1.0);pl_alabel_r (plotter, ’r’, ’x’, "One inch above the bottom");pl_fline_r (plotter, 1.0, 1.0, 7.5, 1.0);

pl_closepl_r (plotter); /* end page of graphics */pl_deletepl_r (plotter); /* delete Plotter */return 0;

}

The programwill print two stringsanddraw the baselinefor each. The first string will be left-justifiedatposition(1.0,11.0),whichis oneinchbelow thetopof thepage.Thesecondstringwill beright-justifiedatposition(7.5,1.0),whichis oneinchabovethebottomof thepage.For bothstrings,the’x’ argumentof pl_alabel_r specifiestheverticalpositioning:it requeststhatthebaselineof thestring,ratherthan(say)its topor bottom,bepositionedat thecurrentverticalposition.

Theprecedingdiscussionandsampleprogramdealtwith theportraitorientationof theprintedpage,which is thedefault. Drawing in landscapeorientationis only slightly morecomplicated.Forthis, the viewport would be rotatedon the pageby settingthe PlotterparameterROTATION. Itsdefault valueis " 0" (or " no" ), andotherallowedvaluesare" 90" (or " yes" ), " 180" , and" 270" .On aletter-sizedpagein landscapeorientation,arotatedviewporthaslower left corner(0.0,0.0)andupperright corner(11.0,8.5),provided that inchesareused.The following programis a modifiedversionof thepreceding,showing how a landscapeorientationwouldbeproduced.

#include <stdio.h>#include <plot.h>

int main(){

plPlotter *plotter;plPlotterParams *plotter_param s;

Page 104: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 99

/* set Plotter parameters */plotter_params = pl_newplparams ();pl_setplparam (plotter_param s, "PAGESIZE",

"letter,xsize=8 .5i n, ys iz e=11i n, xo ri gi n=0in ,y or ig in= 0i n" );pl_setplparam (plotter_param s, "ROTATION", "90");

/* create a Postscript Plotter with the specified parameters */plotter = pl_newpl_r ("ps", stdin, stdout, stderr, plotter_params) ;

pl_openpl_r (plotter); /* begin page of graphics */pl_fspace_r (plotter,

0.0, 0.0, 11.0, 8.5); /* set user coor system */

pl_fontname_r (plotter, "Times-Bold");pl_ffontsize_r (plotter, 0.5); /* font size = 0.5in = 36pt */

pl_fmove_r (plotter, 1.0, 7.5);pl_alabel_r (plotter, ’l’, ’x’, "One inch below the top");pl_fline_r (plotter, 1.0, 7.5, 10.0, 7.5);

pl_fmove_r (plotter, 10.0, 1.0);pl_alabel_r (plotter, ’r’, ’x’, "One inch above the bottom");pl_fline_r (plotter, 1.0, 1.0, 10.0, 1.0);

pl_closepl_r (plotter); /* end page of graphics */pl_deletepl_r (plotter); /* delete Plotter */return 0;

}

It is worthnothingthatrotatingaviewport,by specifyinganonzerovaluefor ROTATION, doesnotchangethepositionof its four corners.Rather, any graphicsthataredrawn arerotatedwithin it.If theviewport is rectangularratherthansquare,this ‘rotation’ necessarilyincludesa rescaling.

9.2.7 AnimatedGIFs in C

UsingGNU libplot to createpseudo-GIFfiles, includinganimatedpseudo-GIFs,is straight-forward. A GIF Plotter is a Plotter like any other, and it supportsthe samedrawing operations.However, it hastwo specialproperties. (1) It candraw only a singlepageof graphics,i.e., onlythegraphicscontainedin the first openpl . . .closepl pair appearin theoutputfile. In this, itresemblesotherPlottersthatdonotplot in realtime. (2) Within thispage,eachinvocationof eraseis normallytreatedasthebeginningof anew imagein theoutputfile. Thereis anexceptionto this:thefirst invocationof erase beginsanew imageonly if somethinghasalreadybeendrawn.

Thereasonfor theexceptionis thatmany programmerswho uselibplot arein thehabitofinvoking erase immediatelyafteraPlotteris opened.Thatis notabadhabit,sincea few typesofPlotter(e.g.,X DrawableandTektronixPlotters)are‘persistent’in thesensethatpreviously drawngraphicsremainvisible.

Thefollowing programcreatesa simpleanimatedpseudo-GIF, 150pixelswide and100pixelshigh.

#include <stdio.h>#include <plot.h>

Page 105: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 100

int main(){

plPlotter *plotter;plPlotterParams *plotter_param s;int i;

/* set Plotter parameters */plotter_params = pl_newplparams ();pl_setplparam (plotter_param s, "BITMAPSIZE", "150x100");pl_setplparam (plotter_param s, "BG_COLOR", "orange");pl_setplparam (plotter_param s, "TRANSPARENT_COLOR", "orange");pl_setplparam (plotter_param s, "GIF_ITERATIONS ", "100");pl_setplparam (plotter_param s, "GIF_DELAY", "5");

/* create a GIF Plotter with the specified parameters */plotter = pl_newpl_r ("gif", stdin, stdout, stderr, plotter_params);

pl_openpl_r (plotter); /* begin page of graphics */pl_fspace_r (plotter,

-0.5, -0.5, 149.5, 99.5); /* set user coor system */

pl_pencolorname _r (plotter, "red"); /* use red pen */pl_linewidth_r (plotter, 5); /* set line thickness */pl_filltype_r (plotter, 1); /* objects will be filled */pl_fillcolornam e_r (plotter, "black"); /* set the fill color */

for (i = 0; i < 180 ; i += 15){

pl_erase_r (plotter); /* begin new GIF image */pl_ellipse_r (plotter, 75, 50, 40, 20, i); /* draw an ellipse */

}

pl_closepl_r (plotter); /* end page of graphics */pl_deletepl_r (plotter); /* delete Plotter */return 0;

}

Theanimatedpseudo-GIFwill be written to standardoutput. It will consistof twelve images,showing the counterclockwiserotation of a black-filled red ellipse through 180 degrees. Thepseudo-GIFwill be‘looped’ (seebelow), sotheellipsewill rotaterepeatedly.

The parametersof the ellipse are expressedin terms of user coordinates,not pixel coordi-nates. But the call to pl_fspace_r definesusercoordinatesthat are effectively the sameaspixel coordinates. In the usercoordinatesystem,the lower left cornerof the rectanglemappedinto the 150x100pseudo-GIFimageis given coordinates( Ö 0.5,Ö 0.5), and the upperright cor-ner is given coordinates(149.5,99.5). So individual pixels may be addressedin termsof inte-gerusercoordinates.For example, invoking pl_point_r(plot te r, 0, 0) andpl_point_r(plotter,149,9 9) wouldsetthepixelsin thelower left andupperright cornersof theimageto thecurrentpencolor.

BesidesBITMAPSIZE andBG_COLOR, thereareseveralimportantGIF Plotterparametersthatmaybesetwith thepl_setplparam function. TheTRANSPARENT_COLORparametermaybe

Page 106: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 101

setto thenameof a color. Pixelsin a pseudo-GIFthathave thatcolor will betreatedastransparentby mostsoftware. This is usuallyusedto createa transparentbackground.In theexampleabove,the backgroundcolor is specifiedasorange,but the transparentcolor is alsospecifiedasorange.Sothebackgroundwill notactuallybedisplayed.

The GIF_ITERATIONS parameter, if set, specifiesthe numberof times that a multi-framepseudo-GIFshouldbelooped.TheGIF_DELAY parameterspecifiesthenumberof hundredthsofasecondsthatshouldelapsebetweensuccessive images.

The INTERLACEparameteris sometimesuseful. If it is setto " yes" , thepseudo-GIFwill beinterlaced.This is of greatestvaluefor single-frameGIFs. For full detailson Plotterparameters,seeSection9.5 [PlotterParameters],page127.

9.2.8 X Window Systemanimationsin C

You may useGNU libplot to producevectorgraphicsanimationson any Plotter that doesreal-timeplotting(i.e.,anX, X Drawable, ReGIS,Tektronix,or MetafilePlotter).By definition,the‘frames’ in any pageof graphicsareseparatedby invocationsof erase . Sothegraphicsdisplaywill beclearedaftereachframe. If successive framesdiffer only slightly, asmoothanimationwillresult.

Thefollowing isasampleapplication,writtenin C, thatproducesananimationfor theX WindowSystem.It displaysa ‘drifting eye’. As theeyedrifts acrossapopped-upwindow from left to right,it slowly rotates.After theeye hasdriftedacrosstwice, thewindow will vanish.

#include <stdio.h>#include <plot.h>

int main (){

plPlotter *plotter;plPlotterParams *plotter_param s;int i = 0, j;

/* set Plotter parameters */plotter_params = pl_newplparams ();pl_setplparam (plotter_param s, "BITMAPSIZE", "300x150");pl_setplparam (plotter_param s, "VANISH_ON_DELETE", "yes");pl_setplparam (plotter_param s, "USE_DOUBLE_BUFFERI NG", "yes");

/* create an X Plotter with the specified parameters */if ((plotter = pl_newpl_r ("X", stdin, stdout, stderr,

plotter_params )) == NULL){

fprintf (stderr, "Couldn’t create Plotter\n");return 1;

}

if (pl_openpl_r (plotter) < 0) /* open Plotter */{

fprintf (stderr, "Couldn’t open Plotter\n");return 1;

}

Page 107: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 102

pl_fspace_r (plotter,-0.5, -0.5, 299.5, 149.5); /* set user coor system */

pl_linewidth_r (plotter, 8); /* set line thickness */pl_filltype_r (plotter, 1); /* objects will be filled */pl_bgcolorname_ r (plotter, "saddle brown"); /* set background color */for (j = 0; j < 300; j++)

{pl_erase_r (plotter); /* erase window */pl_pencolorname _r (plotter, "red"); /* use red pen */pl_fillcolornam e_r (plotter, "cyan"); /* use cyan filling */pl_ellipse_r (plotter, i, 75, 35, 50, i); /* draw an ellipse */pl_colorname_r (plotter, "black"); /* use black pen and filling */pl_circle_r (plotter, i, 75, 12); /* draw a circle [the pupil] */i = (i + 2) % 300; /* shift rightwards */

}if (pl_closepl_r (plotter) < 0) /* close Plotter */

{fprintf (stderr, "Couldn’t close Plotter\n");return 1;

}

if (pl_deletepl_r (plotter) < 0) /* delete Plotter */{

fprintf (stderr, "Couldn’t delete Plotter\n");return 1;

}return 0;

}

As youcansee,thisapplicationbeginsby callingpl_setplparam severaltimesto setPlotterparameters,andthencallspl_newpl_r to createanX Plotter. TheX Plotterwindow will havesize300x150pixels. This window will vanishwhenthe Plotter is deleted. If the VANISH_ON_DELETEparameterwerenot setto " yes" , thewindow would remainon thescreenuntil removedby theuser(by typing ‘q’ in it, or by clicking with amouse).

SettingtheparameterUSE_DOUBLE_BUFFERI NGto " yes" requeststhatdoublebuffering beused.Thisisveryimportantif youwishtoproduceasmoothanimation,with nojerkiness.Normally,anX Plotterdrawsgraphicsinto awindow in realtime,anderasesthewindow whenpl_erase_ris called.But if doublebuffering is used,eachframeof graphicsis written into anoff-screenbuffer,andis copiedinto thewindow, pixel by pixel, whenpl_erase_r is calledor thePlotteris closed.This is abit counterintuitive, but is exactlywhatis neededfor smoothanimation.

After thePlotteris created,it is selectedfor useandopened.Whenpl_openpl_r is called,the window popsup, and the animationbegins. In the body of the for loop thereis a call topl_erase_r , andalsoasequenceof libplot operationsthatdraws theeye. Thepencolorandfill color arechangedtwice with eachpassagethroughtheloop. You maywish to experimentwiththeanimationparametersto producethebesteffectson yourvideohardware.

The positionsof the objectsthat are plotted in the animationare expressedin termsof usercoordinates,notpixel coordinates.But thecall topl_fspace_r definesuserandpixel coordinatesto beeffectively thesame.Usercoordinatesarechosensothatthelower left cornerof therectanglemappedto the X window is ( × 0.5,× 0.5) and the upperright corneris (299.5,149.5).Sincethis

Page 108: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 103

agreeswith thewindow size,individualpixelsmaybeaddressedin termsof integerusercoordinates.For example, pl_point_r(plot te r, 299 ,1 49) would setthepixel in theupperright cornerof thewindow to thecurrentpencolor.

Thefollowing is anothersampleanimation,this timeof a rotatingletter‘A’.

#include <stdio.h>#include <plot.h>

int main(){

plPlotter *plotter;plPlotterParams *plotter_param s;int angle = 0;

/* set Plotter parameters */plotter_params = pl_newplparams ();pl_setplparam (plotter_param s, "BITMAPSIZE", "300x300");pl_setplparam (plotter_param s, "USE_DOUBLE_BUFFERI NG", "yes");pl_setplparam (plotter_param s, "BG_COLOR", "blue");

/* create an X Plotter with the specified parameters */plotter = pl_newpl_r ("X", stdin, stdout, stderr, plotter_params);

/* open X Plotter, initialize coordinates, pen, and font */pl_openpl_r (plotter);pl_fspace_r (plotter, 0.0, 0.0, 1.0, 1.0); /* use normalized coors */pl_pencolorname _r (plotter, "white");pl_ffontsize_r (plotter, 1.0);pl_fontname_r (plotter, "NewCenturySchl bk -Ro man" );

pl_fmove_r (plotter, 0.5, 0.5); /* move to center */while (1) /* loop endlessly */

{pl_erase_r (plotter);pl_textangle_r (plotter, angle++); /* set new rotation angle */pl_alabel_r (plotter, ’c’, ’c’, "A"); /* draw a centered ‘A’ */

}pl_closepl_r (plotter); /* close Plotter */

pl_deletepl_r (plotter); /* delete Plotter */return 0;

}

This animationservesasa goodtestof thecapabilitiesof anX Window Systemdisplay. On amodernX11R6 display, animationwill be smoothandfast. That is becauseX11R6 displayscanrasterizeindividualcharactersfrom afont withoutrasterizingtheentirefont. If yourX displaydoesnotsupportthe" NewCenturySchlbk-Roman" font, youmaysubstituteany otherscalablefont,suchasthewidely available" utopia-medium-r-normal" . For theformatof font names,seeSectionA.3[Text Fontsin X], page140. If theX Plotteris unableto retrieve the font you specify, it will firstattemptto usea default scalablefont (" Helvetica" ). If that too fails, it will usea default Hersheyvectorfont (" HersheySerif" ) instead.

Page 109: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 104

AnimationsthatuseHershey fontsarenormallyfasterthanonesthatusePostscriptfontsor otherX Window Systemfonts,sincetheHershey fontsareconstructedfrom line segments.Rasterizingline segmentscanbe donerapidly. But if you usea scalablefont suchas " NewCenturySchlbk-Roman" or " utopia-medium-r-normal" , you will noticethat the rotationspeedsup after the letter‘A’ hasrotatedthrough360degrees.That is becausethe‘A’ at anglespast360degreeshasalreadybeenrasterized.

If you arewriting anapplicationthatperformsa lengthysequenceof drawing operationson anX Plotter, youmayfind it usefulto setthePlotterparameterX_AUTO_FLUSHto " no" . By default,anX Plotterflushesall graphicsto its X Window Systemdisplayaftereachdrawing operation.Thisflushingensuresthat graphicsarevisible to the userimmediatelyafter they aredrawn. However,it sometimesconsiderablyslows down the renderingprocess. For additionaldetailson Plotterparameters,seeSection9.5[PlotterParameters],page127.

9.2.9 AdvancedX Window Systemprogramming

ApplicationsthatrunundertheX Window Systemareoftenbuilt usingXt, theX Toolkit. In Xt,anapplicationis constructedfrom ‘widgets’ suchastext entryfields,buttons,sliders,drawing areas,etc. Whentheapplicationstartsup, eachwidgetis configuredto respondappropriatelyto ‘events’,whichincludekey pressesandmouseclicks. After thewidgetsareconfigured,controlis transferredto theXt eventloop.

GNU libplot canbeusedwithin theXt eventloopto draw vectorgraphics.For this, it woulduseone or more X Drawable Plotters. An X Drawable Plotter is a Plotter that can plot into anoff-screenpixmapor anon-screenwindow, suchasa window associatedwith awidget.

The following sampleapplicationshows how an X Drawable Plotter would be used. Theapplicationdraws a ‘C’ curve, asdefinedin a previoussection,in a popped-upwindow. TheusualXt command-lineoptionsmaybeused: thewindow backgroundcolor is specifiedwith the ‘ -bg ’option, the window geometrywith ‘ -geometry ’, etc. The curve is initially drawn in red, butclicking oncewith themousewill redraw it in green. A secondmouseclick will redraw it in red,andsoforth. Theapplicationwill terminatewhen‘q’ is typed.

#include <stdio.h>#include <plot.h>#include <X11/Xlib.h>#include <X11/Intrinsic. h>#include <X11/Shell.h>#include <X11/StringDefs .h >#include <X11/Core.h>

plPlotter *plotter;int green = 0; /* draw in green, not red? */

#define MAXORDER12void draw_c_curve (double dx, double dy, int order){

if (order >= MAXORDER)/* continue path along (dx, dy) */pl_fcontrel_r (plotter, dx, dy);

Page 110: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 105

else{

draw_c_curve (0.5 * (dx - dy), 0.5 * (dx + dy), order + 1);draw_c_curve (0.5 * (dx + dy), 0.5 * (dy - dx), order + 1);

}}

void Redraw (Widget w, XEvent *ev, String *params, Cardinal *n_params){

/* draw C curve */pl_erase_r (plotter);pl_pencolorname _r (plotter, green ? "green" : "red");pl_fmove_r (plotter, 600.0, 300.0);draw_c_curve (0.0, 400.0, 0);pl_endpath_r (plotter);

}

void Toggle (Widget w, XEvent *ev, String *params, Cardinal *n_params){

green = (green ? 0 : 1);Redraw (w, ev, params, n_params);

}

void Quit (Widget w, XEvent *ev, String *params, Cardinal *n_params){

exit (0);}

/* mapping of events to actions */static const String translations ="<Expose>: redraw()\n\<Btn1Down>: toggle()\n\<Key>q: quit()";

/* mapping of actions to subroutines */static XtActionsRec actions[] ={

{"redraw", Redraw},{"toggle", Toggle},{"quit", Quit},

};

/* default parameters for widgets */static String default_resour ce s[ ] ={

"Example*geomet ry : 250x250",(String)NULL

};

Page 111: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 106

int main (int argc, char *argv[]){

plPlotterParams *plotter_param s;Arg wargs[10]; /* storage of widget args */Display *display; /* X display */Widget shell, canvas; /* toplevel widget; child */Window window; /* child widget’s window */XtAppContext app_con; /* application context */int i;char *bg_colorname = "white";

/* take background color from command line */for (i = 0; i < argc - 1; i++)

if (strcmp (argv[i], "-bg") == 0)bg_colorname = argv[i + 1];

/* create toplevel shell widget */shell = XtAppInitialize (&app_con,

(String)"Examp le ", /* app class */NULL, /* options */(Cardinal)0, /* num of options */&argc, /* command line */argv, /* command line */default_resour ce s,NULL, /* ArgList */(Cardinal)0 /* num of Args */);

/* set default widget parameters (including window size) */XtAppSetFallbac kRes our ce s (app_con, default_resour ce s);/* map actions to subroutines */XtAppAddActions (app_con, actions, XtNumber (actions));/* create canvas widget as child of shell widget; realize both */XtSetArg(wargs[ 0] , XtNargc, argc);XtSetArg(wargs[ 1] , XtNargv, argv);canvas = XtCreateManaged Widget ((String)"", coreWidgetClass ,

shell, wargs, (Cardinal)2);XtRealizeWidget (shell);/* for the canvas widget, map events to actions */XtSetArg (wargs[0], XtNtranslations ,

XtParseTransla ti onTable (translations) );XtSetValues (canvas, wargs, (Cardinal)1);

/* initialize GNU libplot */plotter_params = pl_newplparams ();display = XtDisplay (canvas);window = XtWindow (canvas);pl_setplparam (plotter_param s, "XDRAWABLE_DISPLAY" , display);pl_setplparam (plotter_param s, "XDRAWABLE_DRAWABLE1" , &window);pl_setplparam (plotter_param s, "BG_COLOR", bg_colorname);

Page 112: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 107

plotter = pl_newpl_r ("Xdrawable", NULL, NULL, stderr,plotter_params) ;

pl_openpl_r (plotter);pl_fspace_r (plotter, 0.0, 0.0, 1000.0, 1000.0);pl_flinewidth_r (plotter, 0.25);

/* transfer control to X Toolkit event loop (doesn’t return) */XtAppMainLoop (app_con);

return 1;}

Evenif youarenotfamiliarwithX Window Systemprogramming,thestructureof thisapplicationshouldbe clear. It definesthreecallbacks: Redraw , Toggle , and Quit . They are invokedrespectively in responseto (1) a window exposeeventor mouseclick, (2) a mouseclick, and(3) atyped‘q’. Thefirst drawing of the ‘C’ curve (in red) takesplacebecausethewindow receivesaninitial exposeevent.

This examplecould be extendedto take window resizinginto account. Actually, X DrawablePlottersare usually usedto draw vector graphicsin off-screenpixmapsrather than on-screenwindows. Pixmaps,unlike windows,arenever resized.

9.3 C++ Programmingwith libplotter

9.3.1 The Plotter class

The C++ binding for libplot is provided by a classlibrary namedlibplotter . Thislibrary implementsa Plotter classof which all Plottersareinstances.Actually, a Plotterwouldnormallybeaninstanceof anappropriatederivedclass,determinedby thePlotter’s outputformat.Derived classesinclude XPlotter , XDrawablePlotte r , PNGPlotter , PNMPlotter ,GIFPlotter , AIPlotter , PSPlotter , CGMPlotter , FigPlotter , PCLPlotter ,HPGLPlotter , ReGISPlotter , TekPlotter , andMetaPlotter . The namesshouldbeself-explanatory. The operationsthat may be appliedto any Plotter(e.g.,the openpl operation,which begins a pageof graphics)are implementedaspublic function membersof the Plotterclass.

At thetimeaPlotteris created,its input,output,anderrorstreamsmustbespecified,alongwith aPlotterParamsobjectthatoptionallycontainsotherPlotterparameters.(Theinputstreamis ignored,sinceat present, all Plottersarewrite-only.) Thestreamsmaybespecifiedeitherasiostreamsor asFILE pointers.Thatis, thetwo constructors

Plotter(istream & instream, ostream& outstream, ostream& errstream,PlotterParams &params);

Plotter(FILE *infile, FILE *outfile, FILE *errfile,PlotterParams &params);

areprovidedfor thebasePlotterclass,andsimilarly for eachof its derivedclasses.So,for example,both

PSPlotter plotter(cin, cout, cerr, params);

and

PSPlotter plotter(stdin, stdout, stderr, params);

Page 113: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 108

arepossibledeclarationsof a PostscriptPlotterthatwritesto standardoutput. In theiostreamcase,anostreamwith anull streambuffer maybespecifiedastheoutputstreamand/ortheerrorstream,torequestthatno outputtake place. In theFILE pointercase,specifyinga null FILE pointerwouldaccomplishthesamething. Instancesof theXPlotter andXDrawablePlotter classesalwaysignoretheoutputstreamargument,sincethey write graphicsto anX Displayratherthanto astream.

The PlotterParams classsupportscopying andassignment,but hasonly a single publicfunctionmember, setplparam . Thefollowing is a formaldescription.

int PlotterParams: :s etp lp ar am(constchar*parameter, void *value);Setthevalueof thePlotterparameterparameterto value. For mostparameters,valueshouldbe a char * , i.e., a string. Unrecognizedparametersareignored. For a listof therecognizedparametersandtheir meaning,seeSection9.5 [PlotterParameters],page127.

Like theplPlotterParams datatypeandthefunctionpl_setplparam of theC binding,the PlotterParams classand the PlotterParams: :se tp lp ar am function of the C++bindinggive theprogrammerfinecontrolover theparametersof subsequentlycreatedPlotters.Theparametervaluesusedby any Plotterareconstantover thelifetime of thePlotter, andarethosethatwerespecifiedwhenthe Plotterwascreated. If at Plottercreationtime a parameterhasnot beensetin thespecifiedPlotterParams object,its default valuewill beused,unlesstheparameterisstring-valuedandthereis anenvironmentvariableof thesamename,in whichcasethevalueof thatenvironmentvariablewill beused.

Oncesetin a PlotterParamsobject,aparametermay be unsetby theprogrammerby invokingPlotterParams:: se tp lp ara m with a value argumentof NULL. This further increasesflexibility.

Thereis an alternative (older) way of constructinga Plotter, which is deprecatedbut still sup-ported.By usingeitherof

Plotter(istream & instream, ostream& outstream, ostream& errstream);Plotter(FILE *infile, FILE *outfile, FILE *errfile);

onemay constructa Plotterwithout specifyinga PlotterParamsobject. In this casethe parametervaluesfor the Plotterarecopiedfrom staticstorage.A parametermay be set in staticstoragebyinvokingastaticmemberfunctionof thePlotter class,Plotter::paramp l ,whichhasdeclaration

int PlotterParams: :p ara mpl (constchar*parameter, void *value);

Thisalternative wayof creatinga Plotteris not thread-safe,which is why it is deprecated.

9.3.2 C++ compiling andlinking

Thesourcecodefor a graphicsapplicationwritten in C++, if it is to uselibplotter , mustcontaintheline

#include <plotter.h>

The headerfile plotter.h is distributed with libplotter , and shouldhave beeninstalledon your systemwhereyour C++ compiler will find it. It declaresthe Plotter classand itsderived classes,and also containssomemiscellaneousdefinitions. It includesthe headerfiles<iostream.h> and<stdio.h> , soyoudo notneedto includethemseparately.

To link your applicationwith libplotter , you would usetheappropriate‘ -l ’ option(s)onthecommandline whencompilingit. You woulduse

Page 114: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 109

-lplotter -lXaw -lXmu -lXt -lXext -lX11 -lpng -lz -lm

or, in recentreleasesof theX Window System,

-lplotter -lXaw -lXmu -lXt -lSM -lICE -lXext -lX11 -lpng -lz -lm

Theselinking optionsassumethat your versionof libplotter hasbeencompiledwith PNGsupport;if not, youwouldomit the‘ -lpng -lz ’ options.

As an alternative to the preceding,you may needto use‘ -lplotter -lXm -lXt -lXext-lX11 -lpng -lz -lm ’, ‘ -lplotter -lXm -lXt -lXext -lX11 -lpng -lz -lm -lc-lgen ’, or ‘ -lplotter -lXm -lXt -lXext -lX11 -lpng -lz -lm -lc -lPW ’, onsystemsthatprovide Motif widgetsinsteadof Athenawidgets.In recentreleasesof theX WindowSystem,you would insert‘ -lSM -lICE ’. Recentreleasesof Motif require‘ -lXp ’ andpossibly‘ -lXpm ’ aswell.)

Onsomeplatforms,thedirectoriesin which libplotter or theotherlibrariesarestoredmustbespecifiedon thecommandline. For example, theoptions‘ -lXaw -lXmu -lXt -lSM -lICE-lXext -lX11 ’, whichspecifyX Window Systemlibraries,mayneedto beprecededby anoptionlike ‘ -L/usr/X11/lib ’.

Onmostsystemslibplotter is installedasasharedlibrary. Thismeansthatthelinking withyour applicationwill take placeat run time ratherthancompile time. The environmentvariableLD_LIBRARY_PATHlists thedirectorieswhich will besearchedfor sharedlibrariesat run time.For your applicationto be executable,this environmentvariableshouldinclude the directory inwhich libplotter is stored.

9.3.3 Sampledrawings in C++

In aprevioussection,thereareseveralsampleC programsthatshow how to draw vectorgraphicsusing libplot ’s C binding. SeeSection9.2.4 [SampleC Drawings], page91. In this section,we give a modifiedversionof oneof theC programs,showing how libplot ’sC++ binding,i.e.,libplotter , canbeusedsimilarly.

Thefollowing C++ programdraws anintricateandbeautifulpath(Bill Gosper’s “C” curve).

#include <plotter.h>const int maxorder = 12;

void draw_c_curve (Plotter& plotter, double dx, double dy, int order){

if (order >= maxorder)plotter.fcontre l (dx, dy); // continue path along (dx, dy)

else{

draw_c_curve (plotter,0.5 * (dx - dy), 0.5 * (dx + dy), order + 1);

draw_c_curve (plotter,0.5 * (dx + dy), 0.5 * (dy - dx), order + 1);

}}

Page 115: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 110

int main (){

// set a Plotter parameterPlotterParams params;params.setplpar am ("PAGESIZE", (char *)"letter");

PSPlotter plotter(cin, cout, cerr, params); // declare Plotterif (plotter.openp l () < 0) // open Plotter

{cerr << "Couldn’t open Plotter\n";return 1;

}

plotter.fspace (0.0, 0.0, 1000.0, 1000.0); // specify user coor systemplotter.flinewi dt h (0.25); // line thickness in user coordinatesplotter.pencolo rn ame ("red"); // path will be drawn in redplotter.erase (); // erase Plotter’s graphics displayplotter.fmove (600.0, 300.0); // position the graphics cursordraw_c_curve (plotter, 0.0, 400.0, 0);if (plotter.close pl () < 0) // close Plotter

{cerr << "Couldn’t close Plotter\n";return 1;

}return 0;

}

Theabove is a straightforward translationof thecorrespondingC program. Here,plotter isdeclaredasaninstanceof thePSPlotter class,whichwill write Postscriptgraphicsto theoutputstreamcout . Thegraphicsaredrawn by invoking memberfunctions.

9.4 The functionsin libplot : A detailedlisting

In thecurrentreleaseof GNU libplot , any Plottersupports97distinctoperations.A languagebindingfor libplot necessarilyincludes97 functionsthatcorrespondto theseoperations.In theC binding,these97 functionsbelongto theC API (applicationprogramminginterface).Thenameof eachfunction begins with the prefix " pl " andendswith the suffix " r" . In theC++ binding,the97 functionsareimplementedaspublic membersof thePlotter class.No prefix or suffix isused.

A languagebindingmayalsoincludefunctionsfor creating,selecting,anddeletingPlotters.Forexample,the C binding includesthe additionalfunctionspl_newpl_r andpl_deletepl_r .SeeSection9.2.1[TheC API], page87.

The97functionsthatoperateonaspecifiedPlotteraredividedinto thefour setstabulatedbelow.

1. Controlfunctions:functionsthatopen,initialize, or closethePlotter.

2. FunctionsthatcausethePlotterto draw objects.

3. Functionsthatsetor affect thePlotter’s drawing attributes.

4. Functionsthatalter theaffine mapusedby thePlotterto transformusercoordinatesto devicecoordinates.

Page 116: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 111

Many functionscomein two versions: integer anddoubleprecisionfloating point. Internally,libplot usesdoubleprecisionfloating point. The integer versionsareprovided for backwardcompatibility. If therearetwo versionsof a function,thenameof thefloatingpoint versionbeginswith theletter‘ f ’.

Many functions come in both absoluteand relative versions,also. The latter use relativecoordinates(i.e.,coordinatesrelative to thecurrentpositionof thegraphicscursor),andtheirnamesendin ‘ rel ’.

Currently, only a few of the97 functionshave meaningfulreturnvalues.

9.4.1 Control functions

Thefollowing arethe“control functions”in libplot . They arethebasicfunctionsthatopen,initialize, or closeanalready-createdPlotter. They arelistedin theapproximateorderin whichtheywouldbecalled.

In the currentC binding, eachof thesefunctionstakesa pointer to a plPlotter asits firstargument. Also in the currentC binding, the nameof eachfunction begins with " pl " andendswith " r" . (" r" standsfor ‘revised’ or ‘reentrant’.) For information on older C bindings, seeSection9.2.2 [Older C APIs], page89. In the C++ binding, thesearememberfunctionsof thePlotter classandits subclasses,andtheprefixandsuffix arenotused.

int openpl ();openpl opensa Plotter, i.e., begins a pageof graphics. This resetsthe Plotter’sdrawing attributesto their default values.A negative returnvalueindicatesthePlottercouldnotbeopened.

Currently, an X Plotterpopsup a new window on an X Window Systemdisplayforeachpageof graphics,i.e., with eachinvocationof openpl . Futurereleasesmaysupportwindow re-use.

int bgcolor (int red, int green, int blue);bgcolor setsthebackgroundcolor for thePlotter’s graphicsdisplay, usinga 48-bitRGBcolormodel.Theargumentsred, greenandbluespecifythered,greenandbluein-tensitiesof thebackgroundcolor. Eachis anintegerin therange0x0000 . . .0xffff ,i.e., 0. . .65535. The choice(0, 0, 0) signifiesblack, andthe choice(65535,65535,65535)signifieswhite.

bgcolor affectsonly Plottersthathaveanotionof backgroundcolor, i.e.,X Plotters,X Drawable Plotters,PNG Plotters,PNM Plotters,and GIF Plotters(all of whichproducebitmaps),CGM Plotters,ReGISPlottersandMetafile Plotters. Its effect issimple: thenext timetheerase operationis invokedonsuchaPlotter, its displaywillbefilled with thespecifiedcolor.

int bgcolorname (constchar*name);bgcolorname setsthe backgroundcolor for the the graphicsdisplay to be name.Unrecognizedcolorsareinterpretedas" white" . For informationonwhatcolornamesarerecognized,seeAppendixB [Color Names],page155. A 24-bit RGB color mayalsobespecifiedasasix-digit hexadecimalstring,e.g.," #c0c0c0" .

bgcolorname affects only Plottersthat have a notion of backgroundcolor, i.e.,X Plotters, X DrawablePlotters,PNG Plotters,PNM Plotters,andGIF Plotters(all

Page 117: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 112

of which producebitmaps),CGM Plotters,ReGISPlotters,andMetafilePlotters. Itseffect is simple: thenext time the erase operationis invoked on sucha Plotter, itsdisplaywill befilled with thespecifiedcolor.

SVG PlottersandCGM Plotterssupport" none" asa valuefor thebackgroundcolor.It will turnoff thebackground:thedrawn objectswill notbebackedby anything. Thisis usefulwhenthegeneratedSVG or WebCGMfile is to beplacedon aWebpage.

int erase ();erase beginsthenext frameof a multiframepage,by clearingall previously plottedobjectsfrom thegraphicsdisplay, andfilling it with thebackgroundcolor (if any).

It is frequentlyusefulto invokeerase atthebeginningof eachpage,i.e.,immediatelyafterinvoking openpl . Thatis becausesomePlottersarepersistent,in thesensethatobjectsdrawn within an openpl . . .closepl pair remainon the graphicsdisplayevenafteranew pageis begunby asubsequentinvocationof openpl . Currently, onlyX DrawablePlottersandTektronixPlottersarepersistent.Futurereleasesmaysupportoptionalpersistencefor X Plottersalso.

OnX PlottersandX DrawablePlotterstheeffectsof invokingerase will bealtogetherdifferentif thePlotterparameterUSE_DOUBLE_BUFFERINGis setto " yes" . In thiscase,objectswill bewritten to anoff-screenbuffer ratherthanto thegraphicsdisplay,and invoking erase will (1) copy the contentsof this buffer to the display, and(2) erasethe buffer by filling it with the backgroundcolor. This ‘double buffering’featurefacilitatessmoothanimation.SeeSection9.5 [PlotterParameters],page127.

int space (int x0, int y0, int x1, int y1);int fspace (doublex0, doubley0, doublex1, doubley1);

space andfspace taketwo pairsof arguments,specifyingthepositionsof thelowerleft andupperright cornersof a rectangularwindow in theusercoordinatesystemthatwill be mappedto the ‘viewport’: the rectangularportion of the outputdevice thatgraphicswill bedrawn in. Thedefaultwindow is asquare,with oppositecorners(0,0)and(1,1).

In mathematicalterms,callingspace or fspace setstheaffine transformationfromuser coordinatesto device coordinates. That is, it setsthe transformationmatrixattributefor eachobjectsubsequentlydrawn onthedisplay. Eitherspace or fspacewould usuallybeinvokedat thebeginningof eachpageof graphics,i.e., immediatelyafterthecall toopenpl . Additionalcallstospace or fspace areallowed,andthereareseveral“mappingfunctions”thatalsoaffectthetransformationmatrixattribute. SeeSection9.4.4[MappingFunctions],page125.

Notethatthesizeandlocationof theviewportdependonthetypeof Plotter, andonthePlotterparametersthatarespecifiedat Plottercreationtime. For example,thedefaultviewport usedby any Illustrator, Postscript,Fig, PCL, andHP-GL Plotteris a squarewhosesizedependson thePlotter’s pagetype. SeeAppendixC [PageandViewportSizes],page156.

int space2 (int x0, int y0, int x1, int y1, int x2, int y2);int fspace2 (doublex0, doubley0, doublex1, doubley1, doublex2, doubley2);

space2 andfspace2 areextendedversionsof space andfspace . Their argu-mentsarethe threedefiningverticesof an parallelogram-shapedwindow in the usercoordinatesystem.Thespecifiedverticesarethe lower left, the lower right, andthe

Page 118: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 113

upperleft. This window will be mappedaffinely onto the viewport: the rectangularportionof theoutputdevice thatgraphicswill bedrawn in.

int havecap (constchar*s);havecap is notreallyacontrolfunction: it is aqueryfunction. It testswhetheror nota Plotter, which neednot beopen,hasa specifiedcapability. Thereturnvalueis 0, 1,or 2, signifying no/yes/maybe.For unrecognizedcapabilitiesthereturnvalueis zero.Recognizedcapabilitiesinclude" WIDE LINES" (i.e., theability to draw lineswitha non-default thickness)," DASH ARRAY" (theability to draw in arbitrarydashingstyles,as requestedby the linedash function), " SETTABLE BACKGROUND"(the ability to set the color of the background),and " SOLID FILL " . The " HER-SHEY FONTS" , " PS FONTS" , " PCL FONTS" , and " STICK FONTS" capabili-ties indicatewhetheror not fontsof a particularclassaresupported.SeeSectionA.1[Text Fonts],page134.

All Plottersexcept Tektronix Plottershave the " SOLID FILL " capability, mean-ing they can fill pathswith solid color. EachsuchPlotter hasat leastone of the" EVEN ODD FILL " and " NONZERO WINDING NUMBER FILL " capabilities.Theseindicatethesupportedrulesfor determiningthe‘inside’ of a path.

The‘maybe’ valueis returnedfor mostcapabilitiesby MetafilePlotters,which do nodrawing themselves. The outputof a Metafile Plottermustbe translatedto anotherformat,or displayed,by invoking plot .

int flushpl ();flushpl flushes(i.e., pushesonward)all previously plottedobjectsto thegraphicsdisplay. This is usefulonly if the affectedPlotter is onethat doesreal-timeplotting(X Plotters, X Drawable Plotters,ReGIS Plotters,Tektronix Plotters,and MetafilePlotters).It ensuresthatall previouslyplottedobjectsarevisibletotheuser. On Plottersthatdo notdo real-timeplotting, thisoperationhasnoeffect.

int closepl ();closepl closesa Plotter, i.e., endsa pageof graphics. If a path is in progress,itis first endedandplotted,as if endpath hadbeencalled. A negative returnvalueindicatesthePlottercouldnotbeclosed.

In the presentreleaseof libplot , somePlottersoutputeachpageof graphicsim-mediatelyafter it is plotted, i.e., whenclosepl is invoked to end the page. Thatis thecasewith PCL andHP-GL Plotters,in particular. Plottersthatcanoutputonlya singlepageof graphics(PNG,PNM, GIF, SVG, Illustrator, andFig Plotters)do soimmediatelyafterthefirst pageis plotted,i.e.,whenclosepl is invokedfor thefirsttime. PostscriptandCGM Plottersstoreall pagesof graphicsinternally, anddo notproduceoutputuntil they aredeleted.

9.4.2 Object-drawing functions

The following are the “drawing functions” in libplot . When invoked on a Plotter, thesefunctionscauseit to draw objects(paths,text strings,marker symbols,andpoints[i.e., pixels]) ontheassociatedgraphicsdisplay.

Pathsmaybesimpleor compound.A simplepathis asequenceof contiguousline segments,arcsegments(eithercircularor elliptic), and/orBeziercurvesegments(eitherquadraticor cubic). Such

Page 119: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 114

simplepathsaredrawn incrementally, onesegmentat a time. A simplepathmayalsobea circle,rectangle,or ellipse.A compoundpathconsistsof multiple simplepaths,whichmustbenested.

Youdonotneedtobegin apathbycallingany specialfunction.Youshould,at leastin theory, endapathunderconstruction,andrequestthatit bedrawn onthegraphicsdisplay, by callingendpath .But theendpath functionis automaticallycalledwhenany otherobjectis drawn, andat theendofeachpageof graphics.It is alsocalledautomaticallywhenany path-relatedattributeis changed:forexample,whenmove is calledto changethegraphicscursorposition.Soendpath seldomneedsto beinvokedexplicitly.

Whendrawing a compoundpath,you would endeachof its constituentsimplepathsby callingendsubpath , and the compoundpath as a whole by calling endpath . After eachcall toendsubpath , you areallowed to call move to repositionthegraphicscursor, prior to beginningthe next simplepath. Sucha call to move will not automaticallyinvoke endpath . This is anexceptionto theabove rule.

In the currentC binding, eachof thesefunctionstakesa pointer to a plPlotter asits firstargument. Also in the currentC binding, the nameof eachfunction begins with " pl " andendswith " r" . (" r" standsfor ‘revised’ or ‘reentrant’.) For information on older C bindings, seeSection9.2.2 [Older C APIs], page89. In the C++ binding, thesearememberfunctionsof thePlotter classandits subclasses,andtheprefixandsuffix arenotused.

int alabel (int horiz justify, int vert justify, constchar*s);alabel takes threeargumentshoriz justify, vert justify, and s, which specify an‘adjustedlabel,’ i.e., a justified text string. The path underconstruction(if any) isendedanddrawn, asif endpath hadbeencalled,andthestrings is drawn accordingto thespecifiedjustifications.If horiz justify is equalto ‘ l ’, ‘c ’, or ‘ r ’, thenthestringwill be drawn with left, centeror right justification, relative to the currentgraphicscursorposition. If vert justify is equalto ‘b’, ‘x ’, ‘c ’, ‘C’, or ‘ t ’, thenthe bottom,baseline,center, cap line, or top of the string will be placedeven with the currentgraphicscursorposition.Thegraphicscursoris movedto theright endof thestringifleft justificationis specified,andto theleft endif right justificationis specified.

Thestringmaycontainescapesequencesof varioussorts(seeSectionA.4 [Text StringFormat],page141),thoughit shouldnot containline feedsor carriagereturns.In factit shouldincludeonly printablecharacters,from thebyte ranges0x20 . . .0x7e and0xa0 . . .0xff . The string may be plottedat a nonzeroangle,if textangle hasbeencalled.

int arc (int xc, int yc, int x0, int y0, int x1, int y1);int farc (doublexc, doubleyc, doublex0, doubley0, doublex1, doubley1);int arcrel (int xc, int yc, int x0, int y0, int x1, int y1);int farcrel (doublexc, doubleyc, doublex0, doubley0, doublex1, doubley1);

arc andfarc takesix argumentsspecifyingthebeginning(x0, y0), end(x1, y1), andcenter(xc, yc) of acirculararc. If thegraphicscursoris at (x0, y0) andapathis underconstruction,thenthearc is addedto thepath. Otherwisethecurrentpath(if any) isendedanddrawn, asif endpath hadbeencalled,andthearcbeginsa new path. Inall casesthegraphicscursoris movedto (x1, y1).

Thedirectionof thearc(clockwiseor counterclockwise)is determinedby theconven-tion that thearc,centeredat (xc, yc), sweepthroughanangleof at most180degrees.If thethreepointsappearto becollinear, thedirectionis takento becounterclockwise.

Page 120: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 115

If (xc, yc) is not equidistantfrom (x0, y0) and(x1, y1) asit shouldbe, it is correctedby beingmovedto theclosestpoint on theperpendicularbisectorof theline segmentjoining (x0, y0) and(x1, y1). arcrel andfarcrel aresimilar to arc andfarc ,but usecursor-relative coordinates.

int bezier2 (int x0, int y0, int x1, int y1, int x2, int y2);int fbezier2 (doublex0, doubley0, doublex1, doubley1, doublex2, doubley2);int bezier2rel (int x0, int y0, int x1, int y1, int x2, int y2);int fbezier2rel (doublex0, doubley0, doublex1, doubley1, doublex2, doubley2);

bezier2 andfbezier2 take six argumentsspecifyingthebeginningp0=(x0, y0)andendp2=(x2, y2) of a quadraticBeziercurve, andits intermediatecontrol pointp1=(x1, y1). If thegraphicscursoris at p0 anda pathis underconstruction,thenthecurve is addedto thepath.Otherwisethecurrentpath(if any) is endedanddrawn,asifendpath hadbeencalled,andthecurve beginsa new path. In all casesthegraphicscursoris movedto p2 . bezier2rel andfbezier2rel aresimilar to bezier2andfbezier2 , but usecursor-relative coordinates.

ThequadraticBeziercurve is tangentat p0 to theline segmentjoining p0 to p1 , andis tangentat p2 to the line segmentjoining p1 to p2 . Soit fits snuglyinto a trianglewith verticesp0 , p1 , andp2 .

When using a PCL Plotter to draw Bezier curves on a LaserJetIII, you shouldsetthe parameterPCL_BEZIERS to " no" . That is becausethe LaserJetIII, whichwasHewlett–Packard’s first PCL5 printer, doesnot recognizetheBezierinstructionssupportedby laterPCL 5 printers.SeeSection9.5[PlotterParameters],page127.

int bezier3 (int x0, int y0, int x1, int y1, int x2, int y2, int x3, int y3);int fbezier3 (doublex0, doubley0, doublex1, doubley1, doublex2, doubley2, doublex3,doubley3);int bezier3rel (int x0, int y0, int x1, int y1, int x2, int y2, int x3, int y3);int fbezier3rel (doublex0, doubley0, doublex1, doubley1, doublex2, doubley2, doublex3,doubley3);

bezier3 and fbezier3 take eight argumentsspecifyingthe beginning p0=(x0,y0) andendp3=(x3, y3) of a cubicBeziercurve, andits intermediatecontrolpointsp1=(x1, y1) and p2=(x2, y2). If the graphicscursor is atp0 and a path is underconstruction,thenthecurve is addedto thepath. Otherwisethecurrentpath(if any)is endedanddrawn, asif endpath hadbeencalled,andthecurve beginsanew path.In all casesthegraphicscursoris moved to p3 . bezier3rel andfbezier3relaresimilar to bezier3 andfbezier3 , but usecursor-relative coordinates.

ThecubicBeziercurve is tangentat p0 to the line segmentjoining p0 to p1 , andistangentatp3 to theline segmentjoining p2 to p3 . Soit fits snuglyinto aquadranglewith verticesp0 , p1 , p2 , andp3 .

When using a PCL Plotter to draw Bezier curves on a LaserJetIII, you shouldsetthe parameterPCL_BEZIERS to " no" . That is becausethe LaserJetIII, whichwasHewlett–Packard’s first PCL5 printer, doesnot recognizetheBezierinstructionssupportedby laterPCL 5 printers.SeeSection9.5[PlotterParameters],page127.

Page 121: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 116

int box (int x1, int y1, int x2, int y2);int fbox (doublex1, doubley1, doublex2, doubley2);int boxrel (int x1, int y1, int x2, int y2);int fboxrel (doublex1, doubley1, doublex2, doubley2);

box andfbox takefourargumentsspecifyingthestartingcorner(x1, y1) andoppositecorner(x2, y2) of a ‘box’, or rectangle.Thepathunderconstruction(if any) is ended,andthebox is drawn asa new path. This pathis alsoended,andthegraphicscursoris movedto themidpointof thebox. boxrel andfboxrel aresimilar to box andfbox , but usecursor-relative coordinates.

int circle (int xc, int yc, int r);int fcircle (doublexc, doubleyc, doubler);int circlerel (int xc, int yc, int r);int fcirclerel (doublexc, doubleyc, doubler);

circle andfcircle take threeargumentsspecifyingthecenter(xc, yc) andradius(r) of a circle. Thepathunderconstruction(if any) is ended,andthecircle is drawnas a new path. This path is also ended,and the graphicscursor is moved to (xc,yc). circlerel andfcirclerel aresimilar to circle andfcircle , but usecursor-relative coordinatesfor xc andyc.

int cont (int x, int y);int fcont (doublex, doubley);int contrel (int x, int y);int fcontrel (doublex, doubley);

cont andfcont take two argumentsspecifyingthecoordinates(x, y) of apoint. If apathis underconstruction,theline segmentfrom thecurrentgraphicscursorpositionto thepoint (x, y) is addedto it. Otherwisetheline segmentbeginsa new path. In allcasesthegraphicscursoris movedto (x, y). contrel andfcontrel aresimilar tocont andfcont , but usecursor-relative coordinates.

int ellarc (int xc, int yc, int x0, int y0, int x1, int y1);int fellarc (doublexc, doubleyc, doublex0, doubley0, doublex1, doubley1);int ellarcrel (int xc, int yc, int x0, int y0, int x1, int y1);int fellarcrel (doublexc, doubleyc, doublex0, doubley0, doublex1, doubley1);

ellarc and fellarc take six argumentsspecifyingthe threepointspc =(xc,yc),p0=(x0,y0), andp1=(x1,y1) thatdefinea so-calledquarterellipse. This is anellipticarc from p0 to p1 with centerpc . If the graphicscursoris at point p0 anda pathis underconstruction,the quarter-ellipse is addedto it. Otherwisethe path underconstruction(if any) is endedand drawn, as if endpath had beencalled, and thequarter-ellipsebeginsanew path. In all casesthegraphicscursoris movedto p1 .

Thequarter-ellipseis anaffinely transformedversionof aquartercircle. It is drawn soasto havecontrolpointsp0 , p1 , andp0+p1 Ø pc . Thismeansthatit is tangentatp0to theline segmentjoining p0 to p0+p1 Ø pc , andis tangentatp1 to theline segmentjoining p1 to p0+p1 Ø pc . Soit fits snuglyinto a trianglewith thesethreecontrolpointsasvertices.Noticethatthethird controlpoint is thereflectionof pc throughtheline joining p0 andp1 . ellarcrel andfellarcrel aresimilar to ellarc andfellarc , but usecursor-relative coordinates.

Page 122: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 117

int ellipse (int xc, int yc, int rx, int ry, int angle);int fellipse (doublexc, doubleyc, doublerx, doublery, doubleangle);int ellipserel (int xc, int yc, int rx, int ry, int angle);int fellipserel (doublexc, doubleyc, doublerx, doublery, doubleangle);

ellipse and fellipse take five argumentsspecifyingthe center(xc, yc) of anellipse,thelengthsof its semiaxes(rx andry), andtheinclinationof thefirst semiaxisin thecounterclockwisedirectionfrom the Ù axis in theusercoordinatesystem.Thepath underconstruction(if any) is ended,and the ellipse is drawn as a new path.This pathis alsoended,andthegraphicscursoris movedto (xc, yc). ellipserelandfellipserel aresimilar to ellipse andfellipse , but usecursor-relativecoordinates.

int endpath ();endpath terminatesthepathunderconstruction,if any, anddraws it. It alsoremovesthepathfrom thecurrentgraphicscontext, sothatanew pathmaybeconstructed.

The pathunderconstructionmay be a simplepath,or a compoundpathconstructedwith the aid of endsubpath (seebelow). A simplepath is constructedby oneormoresuccessive calls to cont , line , arc , ellarc , bezier2 , bezier3 , and/ortheir floating point counterparts.A simplepathmay alsobe constructedby a singlecall to circle , ellipse , or box .

It is often not necessaryto call endpath explicitly, since it is frequently calledautomatically. It will be called if any non-pathobject is drawn, if any path-relateddrawing attribute is set,or if move or fmove is invoked to set the cursorposition.It will alsobe called if restorestate is called to pop a graphicscontext off thestack,andif closepl is calledto enda pageof graphics.Soit is seldomnecessaryto call endpath explicitly. However, if a Plotterplots objectsin real time, callingendpath will ensurethata completedpathis drawn on thegraphicsdisplaywithoutdelay.

int endsubpath ();endsubpath terminatesthesimplepathunderconstruction,if any, andsignalsthattheconstructionof thenext simplepathin a compoundpathis to begin. Immediatelyafterendsubpath is called,it is permissibleto call move or fmove to repositionthegraphicscursor. (At othertimesin thedrawing of a compoundpath,calling move orfmove wouldforceaprematureendtothepath,byautomaticallyinvokingendpath .)

int label (constchar*s);label takesasinglestringarguments anddrawsthetext containedin s at thecurrentgraphicscursorposition.Thetext is left justified,andthegraphicscursoris movedtotheright endof thestring. This function is provided for backwardcompatibility; thefunctioncall label (s) is equivalentto alabel (‘l’,‘x’, s).

int labelwidth (constchar*s);doubleflabelwidth (constchar*s);

labelwidth andflabelwidth arenot really object-drawing functions: they arequeryfunctions.They computeandreturnthewidth of a stringin thecurrentfont, intheusercoordinatesystem.Thestringis notdrawn.

Page 123: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 118

int line (int x1, int y1, int x2, int y2);int fline (doublex1, doubley1, doublex2, doubley2);int linerel (int x1, int y1, int x2, int y2);int flinerel (doublex1, doubley1, doublex2, doubley2);

line andfline takefour argumentsspecifyingthestartpoint(x1, y1) andendpoint(x2, y2) of a line segment. If the graphicscursoris at (x1, y1) anda path is underconstruction,the line segmentis addedto it. Otherwisethe pathunderconstruction(if any) is endedanddrawn, as if endpath hadbeencalled,and the line segmentbegins a new path. In all casesthegraphicscursoris moved to (x2, y2). linerelandflinerel aresimilar to line andfline , but usecursor-relative coordinates.

int marker (int x, int y, int type, int size);int fmarker (doublex, doubley, int type, doublesize);int markerrel (int x, int y, int type, int size);int fmarkerrel (doublex, doubley, int type, doublesize);

marker andfmarker take four argumentsspecifyingtheposition(x,y) of amarkersymbol, its type, and its font size in usercoordinates.The pathunderconstruction(if any) is endedanddrawn, asif endpath hadbeencalled,andthemarkersymbolisplotted. Thegraphicscursoris movedto (x,y). markerrel andfmarkerrel aresimilar to marker andfmarker , but usecursor-relative coordinatesfor theposition(x,y).

A marker symbolis a visualrepresentationof a point,which is visible on all typesofPlotter. In this it differsfrom thepointsproducedby thepoint function(seebelow).Marker symboltypes0. . .31 aretakenfrom a standardset,andmarker symboltypes32 andabove areinterpretedasthe index of a characterin thecurrenttext font. SeeSectionA.5 [Marker Symbols],page153.

int point (int x, int y);int fpoint (doublex, doubley);int pointrel (int x, int y);int fpointrel (doublex, doubley);

point andfpoint take two argumentsspecifyingthecoordinates(x, y) of a point.The pathunderconstruction(if any) is endedanddrawn, as if endpath hadbeencalled,andthepointisplotted.Thegraphicscursorismovedto (x, y). pointrel andfpointrel aresimilar to point andfpoint , but usecursor-relative coordinates.

‘Point’ is a misnomer. Any Plotter that producesa bitmap, i.e., an X Plotter, anX DrawablePlotter, aPNGPlotter, aPNM Plotter, or a GIF Plotter, draws apointasasinglepixel. Most otherPlottersdraw a point asa smallsolid circle, usuallysosmallasto beinvisible. Sopoint shouldreally becalledpixel .

9.4.3 Attribute-settingfunctions

The following are the “attribute functions” in libplot . When invoked on a Plotter, thesefunctionsset its drawing attributes,or save themor restorethem. Path-relatedattributesincludegraphicscursorposition,pencolor, fill color, fill rule, line thickness,line style,capstyle,join style,miter limit, andtransformationmatrix. Text-relatedattributesincludepencolor, font name,fontsize,text angle,andtransformationmatrix.

Page 124: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 119

Settingany path-relateddrawing attribute automaticallyterminatesanddraws the pathunderconstruction(if any), asif the endpath operationhadbeeninvoked. The ‘orientation’ attribute(clockwise/counterclockwise), whichaffectscircles,ellipses,andboxes,is anexceptionto this. Theexceptionallowsacompoundpathto includecircles,ellipses,andboxeswith differentorientations.

In the currentC binding, eachof thesefunctionstakesa pointer to a plPlotter asits firstargument. Also in the currentC binding, the nameof eachfunction begins with " pl " andendswith " r" . (" r" standsfor ‘revised’ or ‘reentrant’.) For information on older C bindings, seeSection9.2.2 [Older C APIs], page89. In the C++ binding, thesearememberfunctionsof thePlotter classandits subclasses,andtheprefixandsuffix arenotused.

int capmod (constchar*s);capmod terminatesanddraws the pathunderconstruction(if any), as if endpathhadbeencalled,andsetsthecapmode(i.e.,capstyle)for all pathssubsequentlydrawnon the graphicsdisplay. Recognizedstylesare " butt" (the default), " round" , and" projecting" . The threestylesarevisibly distinct only if the line thicknessis fairlylarge. Butt capsdo not extendbeyond the endof the path. The othertwo kinds do,however. Roundcapsarefilled semicircles,andprojectingcapsarefilled rectangularregionsthatextendadistanceequalto half theline width beyondtheendof thepath.PNG,PNM, GIF, PCL,andHP-GL Plotterssupporta fourth capmode," triangular" .(For all but PCL andHP-GL Plotters,thesupportis currentlyonly partial.) Plottersotherthanthesetreat" triangular" asequivalentto " round" .This functionhasno effect on ReGISor TektronixPlotters.Also, it hasno effect onHP-GL Plottersif theparameterHPGL_VERSIONis setto a valuelessthan" 2" (thedefault), or on CGM Plottersif theparameterCGM_MAX_VERSIONis setto a valuelessthan" 3" . SeeSection9.5[PlotterParameters],page127.

int color (int red, int green, int blue);color is a conveniencefunction. Calling color is equivalent to calling bothpencolor andfillcolor , to setboththethepencolorandfill colorof all objectssubsequentlydrawn on thegraphicsdisplay. Notethat thephysicalfill color dependsalsoon thefill level, which is specifiedby calling filltype .

int colorname (constchar*name);colorname is aconveniencefunction. Calling colorname is equivalentto callingbothpencolorname andfillcolorname , to setboth the thepencolor andfillcolorof all objectssubsequentlydrawn on thegraphicsdisplay. Notethatthephysicalfill colordependsalsoon thefill level, which is specifiedby calling filltype .

int fillcolor (int red, int green, int blue);fillcolor terminatesanddrawsthepathunderconstruction(if any), asif endpathhadbeencalled,andsetsthefill color for all pathssubsequentlydrawn onthegraphicsdisplay, usinga 48-bit RGB color model. Theargumentsred, greenandblue specifythe red, greenandblue intensitiesof the fill color. Eachis an integer in the range0x0000 . . .0xffff , i.e., 0. . .65535. The choice(0, 0, 0) signifiesblack, andthechoice(65535,65535,65535)signifieswhite. Notethatthephysicalfill colordependsalsoon thefill level, which is specifiedby calling filltype .

int fillcolorname (constchar*name);fillcolorname setsthefill color of all pathssubsequentlydrawn on thegraphicsdisplayto bename. Unrecognizedcolorsareinterpretedas" black" . For information

Page 125: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 120

on what color namesare recognized,seeAppendix B [Color Names],page155.A 24-bit RGB color may also be specifiedas a six-digit hexadecimalstring, e.g.," #c0c0c0" .

Note that the physicalfill color dependsalsoon the fill level, which is specifiedbycalling filltype .

int fillmod (constchar*s);fillmod terminatesanddraws thepathunderconstruction(if any), asif endpathhadbeencalled,andsetsthefill mode,i.e., fill rule, for all pathssubsequentlydrawnonthegraphicsdisplay. Thefill ruleaffectsonly compoundpathsandself-intersectingsimplepaths:it determineswhichpointsare‘inside’. Two rulesaresupported:" even-odd" (thedefault for all Plotters),and" nonzero-winding" . For thedistinction,seethePostscriptLanguageReferenceManual. " alternate" is an aliasfor " even-odd" and" winding" is analiasfor " nonzero-winding" .

CGM, Fig, andReGISPlottersdo not supportthe " nonzero-winding" rule, becausethe CGM, Fig, andReGISvectorgraphicsformatsdo not supportit. Also, HP-GLPlottersdo not support" nonzero-winding" if HPGL_VERSIONis setto a valuelessthan" 2" (thedefault). SeeSection9.5 [PlotterParameters],page127.

TheLaserJetIII, whichwasHewlett–Packard’s first PCL5 printer, did notsupportthenonzero-windingfill rule. However, all later PCL 5 printersfrom Hewlett–Packardsupportit.

int filltype (int level);filltype terminatesanddrawsthepathunderconstruction(if any), asif endpathhad beencalled, and setsthe fill level for all subsequentlydrawn paths. A valueof 0 for level specifiesno filling. This is the default. A value of 1 specifies100%filling: thefill color will bethecolor previously specifiedby calling fillcolor orfillcolorname .

As a convenience to the user, level may be set to any value in the range0x0000 . . .0xffff , i.e., 0. . .65535. Any nonzerovalue will producefilling. Iflevel=0xffff , thefill color will bewhite. Valuesin therange0x0001 . . .0xffffare interpretedas specifyinga desaturation,or gray level. For example, 0x8000specifies50% filling (the fill color will be half-way betweenthe color specifiedbycalling fillcolor or fillcolorname , andwhite).

Todraw theregionboundedbyapathin anedgelessway, youwouldcall filltype toturnonthefilling of theinterior, andpentype to turnoff thedrawing of theboundary.

TektronixPlottersdonotsupportfilling, andHP-GLPlotterssupportfilling of arbitrarypathsonly if theparameterHPGL_VERSIONis equalto " 1.5" or " 2" (thedefault).(If the version is " 1" then only circles and rectanglesalignedwith the coordinateaxes may be filled.) Opaquefilling, including white filling, is supportedonly iftheparameterHPGL_VERSIONis " 2" andtheparameterHPGL_OPAQUE_MODE is" yes" (thedefault). SeeSection9.5[PlotterParameters],page127.

int fmiterlimit (doublelimit );fmiterlimit terminatesand draws the path under construction(if any), as ifendpath hadbeencalled,andsetsthemiter limit for all pathssubsequentlydrawn onthegraphicsdisplay. Themiter limit controlsthetreatmentof corners,if thejoin mode

Page 126: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 121

is setto " miter" (thedefault). At a join point of a path,the ‘miter length’ is definedto bethedistancebetweentheinnercornerandtheoutercorner. Themiter limit is themaximumvaluethatwill betoleratedfor themiter lengthdividedby theline thickness.If this valueis exceeded,themiterwill becut off: the" bevel" join modewill beusedinstead.

Examplesof typical valuesfor limit are10.43(thedefault,whichcutsoff mitersif thejoin angleis lessthan11degrees),2.0(thesame,for 60degrees),and1.414(thesame,for 90 degrees). In general, the miter limit is the cosecantof one-halfthe minimumanglefor miteredjoins. Theminimummeaningfulvaluefor limit is 1.0,whichconvertsall miteredjoins to beveledjoins, irrespective of join angle. Specifyinga valuelessthan1.0resetsthelimit to thedefault.

This functionhasno effectonX DrawablePlottersor X Plotters, sincetheX WindowSystemmiter limit, which is also10.43,cannotbe altered. It alsohasno effect onTektronix, ReGIS,or Fig Plotters,or on HP-GL Plottersif the parameterHPGL_VERSION is set to a value less than" 2" (the default). SeeSection9.5 [PlotterParameters],page127. The miter limit usedby HP-GL or PCL Plottersis alwaysroundedto theclosestinteger, downward.

int fontname (constchar* font name);doubleffontname (constchar* font name);

fontname and ffontname take a single case-insensitive string argument,font name, specifyingthenameof thefont to beusedfor all text stringssubsequentlydrawn on the graphicsdisplay. (The font for plotting strings is fully specifiedbycalling fontname , fontsize , and textangle .) The size of the font in usercoordinatesis returned.

Thedefault font namedependson thetypeof Plotter. It is " Helvetica" for all Plottersexcept for PCL Plotters,for which it is " Univers" , and PNG, PNM, GIF, HP-GL,ReGIS,TektronixandMetafilePlotters,for whichit is" HersheySerif" . If theargumentfont nameis NULL or theemptystring,or the font is not available,the default fontnamewill beused.Which fontsareavailablealsodependsonthetypeof Plotter;for alist of all availablefonts,seeSectionA.1 [Text Fonts],page134.

int fontsize (int size);doubleffontsize (doublesize);

fontsize and ffontsize take a singleargument,interpretedasthe size,in theusercoordinatesystem,of the font to beusedfor all text stringssubsequentlydrawnon the graphicsdisplay. (The font for plotting strings is fully specifiedby callingfontname , fontsize , andtextangle .) Thesizeof thefont in usercoordinatesis returned.

A negative value for size setsthe size to the default, which dependson the type ofPlotter. Typically, thedefault font sizeis 1/50timesthesize(i.e.,minimumdimension)of the display. The interpretationof zero font size is also Plotter-dependent(mostPlottersdonotdraw text stringsif thefont sizeis zero).

int joinmod (constchar*s);joinmod terminatesanddraws thepathunderconstruction(if any), asif endpathhadbeencalled,andsetsthejoin mode(i.e.,join style)for all pathssubsequentlydrawnon the graphicsdisplay. Recognizedstylesare" miter" (the default), " round" , and

Page 127: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 122

" bevel" . Thethreestylesarevisibly distinctonly if the line thicknessis fairly large.Mitered joins aresharp,roundedjoins areround,andbeveled joins aresquaredoff.However, unusuallysharpjoinsarenevermitered:instead,they arebeveled.Theangleatwhichbeveling replacesmiteringmaybespecifiedby calling fmiterlimit .

PNG,PNM, GIF, PCL,andHP-GL Plotterssupporta fourth join mode," triangular" .OtherPlotterstreat" triangular" asequivalentto " round" .

This functionhasno effect on ReGISor TektronixPlotters.Also, it hasno effect onHP-GL Plottersif theparameterHPGL_VERSIONis setto a valuelessthan" 2" (thedefault), or on CGM Plottersif theparameterCGM_MAX_VERSIONis setto a valuelessthan" 3" . SeeSection9.5[PlotterParameters],page127.

int linedash (int n, constint *dashes, int offset);int flinedash (int n, constdouble*dashes, doubleoffset);

linedash andflinedash terminateanddraw thepathunderconstruction(if any),asif endpath hadbeencalled,andsettheline stylefor all pathssubsequentlydrawnon the graphicsdisplay. They provide muchfiner control of dashpatternsthan thelinemod function (seebelow) provides. dashesshouldbeanarrayof lengthn. Itselements,which shouldbepositive, areinterpretedasdistancesin theusercoordinatesystem. Along any path, circle, or ellipse, the elementsdashes[0] . . .dashes[n-1]alternatelyspecifythelengthof adashandthelengthof agapbetweendashes.Whentheendof thearrayis reached,thereadingof thearraywrapsaroundto thebeginning.If thearrayis empty, i.e.,n equalszero,thereis nodashing:thedrawn line is solid.

Theoffset argumentspecifiesthe‘phase’of thedashpatternrelative to thestartof thepath. It is interpretedasthedistanceinto thedashpatternatwhich thedashingshouldbegin. For example,if offset equalszerothenthepathwill begin with adash,of lengthdashes[0] in userspace.If offset equalsdashes[0] thenthepathwill begin with a gapof lengthdashes[1], andsoforth. offset is allowedto benegative.

Not all Plottersfully supportlinedash andflinedash . PCLandHP-GLPlotterscannotdashwith anonzerooffset,andin thedashpatternsusedby X andX DrawablePlotters,eachdashor gap hasa maximumlength of 255 pixels. linedash andflinedash have no effect atall on Tektronix,ReGIS,andFig Plotters. Also, theyhave no effect on HP-GL Plottersfor which the parameterHPGL_VERSIONis lessthan" 2" (the default), or on CGM Plottersfor which the parameterCGM_MAX_VERSIONis lessthan" 3" . For informationon Plotterparameters,seeSection9.5[PlotterParameters],page127.

Warning: If thetransformationfrom theusercoordinatesystemto thedevice coordi-natesystemis anisotropic,eachdashpatternshouldideally bedrawn on thegraphicsdisplay with a length that dependson its direction. But currently, only SVG andPostscriptPlottersdo this. OtherPlottersalwaysdraw any specifieddashpatternwiththesamelength,irrespective of its direction. The lengththat is usedis theminimumlength,in thedevicecoordinatesystem,thatcancorrespondtothespecifieddashpatternlengthin theusercoordinatesystem.

int linemod (constchar*s);linemod terminatesanddraws thepathunderconstruction(if any), asif endpathhadbeencalled,andsetstheline stylefor all pathssubsequentlydrawn onthegraphicsdisplay. Thesupportedlinestylesare" solid" , " dotted" , " dotdashed" , " shortdashed" ,

Page 128: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 123

" longdashed" , " dotdotdashed" , " dotdotdotdashed" , and" disconnected" . The firstsevencorrespondto thefollowing dashpatterns:

"solid" --------------- -- -- -- -- --- -- -- --"dotted" - - - - - - - -"dotdashed" ---- - ---- - ---- -"shortdashed" ---- ---- ---- ----"longdashed" ------- ------- -------"dotdotdashed" ---- - - ---- - -"dotdotdotdashe d" ---- - - - ---- - - -

In theprecedingpatterns,eachhyphenstandsfor oneline thickness.This is thecasefor sufficiently thick lines, at least. Sofor sufficiently thick lines, the distanceoverwhichadashpatternrepeatsis scaledproportionatelyto theline thickness.

The " disconnected" line style is special.A " disconnected" pathis renderedasa setof filled circles,eachof which hasdiameterequalto thenominalline thickness.Oneof thesecirclesis centeredoneachof thejuncturepointsof thepath(i.e., theendpointsof the line segmentsor arcsfrom which it is constructed).Circlesandellipseswith" disconnected" line styleareinvisible. Disconnectedpathsarenotfilled; this includescirclesandellipses.

All linestylesaresupportedbyall Plotters,with thefollowing exceptions.HP-GLPlot-tersdonotsupportthe" dotdotdotdashed" styleunlesstheparameterHPGL_VERSIONis setto " 2" (thedefault). TektronixPlottersdo not supportthe " dotdotdotdashed"style,anddonotsupportthe" dotdotdashed" styleunlesstheparameterTERMis setto" kermit" . SeeSection9.5[PlotterParameters],page127.

int linewidth (int size);int flinewidth (doublesize);

linewidth and flinewidth terminateand draws the path underconstruction(if any), asif endpath hadbeencalled,andsetthethickness,in theusercoordinatesystem,of all pathssubsequentlydrawn on the graphicsdisplay. A negative valueresetsthethicknessto thedefault. Thedefault thicknessdependsonthetypeof Plotter.For mostPlotters,it is 1/850timesthesizeof theviewport, i.e., thedrawn-onportionof thedisplay. (Here‘size’ meansminimumdimension.)But for Plottersthatproducebitmaps,i.e., X Plotters, X DrawablePlotters,PNG Plotters,PNM Plotters,andGIFPlotters,it is zero.

By convention,a zero-thicknessline is thethinnestline thatcanbedrawn. However,thedrawing editorsidraw andxfig treatzero-thicknesslinesasinvisible. Sowhenproducingeditablegraphicswith aPostscriptor Fig Plotter, usingazeroline thicknessmaynotbedesirable.

TektronixandReGISPlottersdo not supportdrawing with otherthana default thick-ness,andHP-GLPlottersdonotsupportdoingsoif theparameterHPGL_VERSIONissettoavaluelessthan" 2" (thedefault;seeSection9.5[PlotterParameters],page127).

Warning: If the transformationfrom the usercoordinatesystemto the device coor-dinatesystemis anisotropic,eachline segmentin a polygonalpathshouldideally bedrawn on thegraphicsdisplaywith a thicknessthatdependson its direction. But cur-rently, only SVG andPostscriptPlottersdo this. OtherPlottersdraw all line segmentsin apathwith thesamethickness.Thethicknessthatis usedis theminimumthickness,

Page 129: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 124

in thedevice coordinatesystem,thatcancorrespondto thespecifiedline thicknessintheusercoordinatesystem.

int move (int x, int y);int fmove (doublex, doubley);int moverel (int x, int y);int fmoverel (doublex, doubley);

move andfmove take two argumentsspecifyingthecoordinates(x, y) of a point towhich the graphicscursorshouldbe moved. The pathunderconstruction(if any) isendedanddrawn, asif endpath hadbeencalled,andthegraphicscursoris movedto(x, y). This is equivalentto lifting thepenonaplotterandmoving it to anew position,withoutdrawing any line. moverel andfmoverel aresimilartomove andfmove ,but usecursor-relative coordinates.

Whena new pageof graphicsis begunby invoking openpl , thecursoris initially atthepoint (0,0) in userspace.Most of thedrawing functionsrepositionthecursor. SeeSection9.4.2[Drawing Functions],page113.

int orientation (int direction);orientation setsthe orientationfor all circles,ellipses,andboxessubsequentlydrawn onthegraphicsdisplay. directionmustbe1, meaningcounterclockwise,or Ú 1,meaningclockwise.Thedefault is 1.

orientation will haveavisibleeffectonacircle,ellipse,or boxonly if it is dashed,or if it is oneof thesimplepathsin afilled compoundpath.Its effectsonfilling, whenthe" nonzero-winding" fill rule is used,aredramatic,sinceit is theorientationof eachsimplepathin a compoundpaththatdetermineswhich pointsare‘inside’ andwhichare‘outside’.

int pencolor (int red, int green, int blue);pencolor terminatesanddrawsthepathunderconstruction(if any), asif endpathhad beencalled, and setsthe pen color for all objectssubsequentlydrawn on thegraphicsdisplay, usinga48-bitRGBcolor model.Theargumentsred, greenandbluespecifythe red,greenandblue intensitiesof thepencolor. Eachis an integer in therange0x0000 . . .0xffff , i.e.,0. . .65535.Thechoice(0, 0, 0) signifiesblack,andthechoice(65535,65535,65535)signifieswhite.

HP-GL Plotterssupportdrawing with a white penonly if thevalueof the parameterHPGL_VERSIONis " 2" (thedefault),andthevalueof theparameterHPGL_OPAQUE_MODEis " yes" (thedefault). SeeSection9.5 [PlotterParameters],page127.

int pencolorname (constchar*name);pencolorname setsthepencolorof all objectssubsequentlydrawn on thegraphicsdisplayto bename. Unrecognizedcolorsareinterpretedas" black" . For informationon what color namesare recognized,seeAppendix B [Color Names],page155.A 24-bit RGB color may also be specifiedas a six-digit hexadecimalstring, e.g.," #c0c0c0" .

HP-GL Plotterssupportdrawing with a white penonly if thevalueof the parameterHPGL_VERSIONis " 2" (thedefault)andthevalueof theparameterHPGL_OPAQUE_MODEis " yes" (thedefault). SeeSection9.5 [PlotterParameters],page127.

Page 130: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 125

int pentype (int level);pentype terminatesanddraws thepathunderconstruction(if any), asif endpathhadbeencalled,andsetsthepenlevel for all subsequentlydrawn paths.A valueof 1for level specifiesthatanoutlineof eachof theseobjectsshouldbedrawn, in thecolorpreviously specifiedby calling pencolor or pencolorname . This is thedefault.A valueof 0 specifiesthatoutlinesshouldnotbedrawn.

To draw theregion boundedby a pathin anedgelessway, you would call pentypeto turnoff the drawing of the boundary, and filltype to turnon the filling of theinterior.

pentype alsoaffectsthedrawing of marker symbolsandpoints,i.e.,pixels. A valueof 0 specifiesthatthey shouldnotbedrawn.

Note: In futurereleases,pentype mayalsoaffect thedrawing of text strings(avalueof 0 will specifythatthey shouldnot bedrawn). It alreadyaffectstext stringsthatarerenderedusingHershey fonts,sincethey aredrawn usingpolygonalpaths.

int restorestate ();restorestate popsthe currentgraphicscontext off the stackof drawing states.Thegraphicscontext consistslargely of libplot ’sdrawing attributes,which aresetby the attribute functionsdocumentedin this section. So poppingoff the graphicscontext restoresthe drawing attributesto valuesthey previously had. A pathunderconstructionis regardedas part of the graphicscontext. For this reason,callingrestorestate automaticallycallsendpath to terminateanddraw thepathunderconstruction,if any. All graphicscontextsonthestackarepoppedoff whencloseplis called,asif restorestate hadbeencalledrepeatedly.

int savestate ();savestate pushesthe currentgraphicscontext onto the stackof drawing states.The graphicscontext consistslargely of libplot ’s drawing attributes, which aresetby theattribute functionsdocumentedin this section. A pathunderconstruction,if any, is regardedaspartof thegraphicscontext. Thatis becausepathsmaybedrawnincrementally, oneline segmentor arcat a time. Thenew graphicscontext createdbysavestate will containno path. Whenthepreviousgraphicscontext is returnedtobycallingrestorestate , thepathpreviouslyunderconstructionmaybecontinued.

int textangle (int angle);doubleftextangle (doubleangle);

textangle and ftextangle take one argument,which specifiesthe angle indegreescounterclockwisefrom the Û (horizontal)axis in theusercoordinatesystem,for text stringssubsequentlydrawn on thegraphicsdisplay. Thedefault angleis zero.(Thefont for plottingstringsis fully specifiedby calling fontname , fontsize , andtextangle .) Thesizeof thefont for plottingstrings,in usercoordinates,is returned.

9.4.4 Mappingfunctions

Thefollowing arethe“mappingfunctions”in libplot . WheninvokedonaPlotter, they affectthe affine transformationit employs to map the usercoordinatesystemto the device coordinatesystem.Thatis, they affect thetransformationmatrixattributeof objectssubsequentlydrawn onthegraphicsdisplay.

Page 131: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 126

The namesof thesefunctionsresemblethoseof the correspondingfunctionsin the Postscriptlanguage.For informationon how to usethemto draw graphicsefficiently, consultany goodbookon Postscriptprogramming,or thePostscriptLanguageReferenceManual.

Eachof thesefunctions,if called,terminatesanddraws thepathunderconstruction(if any), asif endpath hadbeencalled.

In the currentC binding, eachof thesefunctionstakesa pointer to a plPlotter asits firstargument. Also in the currentC binding, the nameof eachfunction begins with " pl " andendswith " r" . (" r" standsfor ‘revised’ or ‘reentrant’.) For information on older C bindings, seeSection9.2.2 [Older C APIs], page89. In the C++ binding, thesearememberfunctionsof thePlotter classandits subclasses,andtheprefixandsuffix arenotused.

int fsetmatrix (doublem0, doublem1, doublem2, doublem3, doubletx, doublety);UsethePostscript-styletransformationmatrix [m0 m1 m2 m3 tx ty] asthetransfor-mationmatrix from userspaceto NDC (normalizeddevice coordinate)space. Thismatrix determinesthe transformationmatrix from userspaceto unnormalizeddevicespace,i.e.,setsthetransformationmatrixattributethatwill beusedwhensubsequentlydrawing objectson thegraphicsdisplay.

In NDC space,the graphicsdisplay (i.e., viewport) has corners(0,0) , (1,0) ,(1,1) , and(0,1) . For informationon thesizeof thegraphicsdisplayin physicalunits,seeAppendixC [PageandViewportSizes],page156.

The default transformationmatrix from user spaceto NDC spaceis [1 0 0 1 0 0],whichmeansthatby default,usercoordinatesarethesameasNDC coordinates.Thistransformationmatrix is alsoalteredby space , fspace , space2 , andfspace2 ,andby thefollowing functions.

int fconcat (doublem0, doublem1, doublem2, doublem3, doubletx, doublety);Modify the transformationmatrix from userspaceto NDC spaceby pre-multiplyingit by thematrix [m0 m1 m2 m3 tx ty]. Equivalently, apply the linear transformationdefinedby thetwo-by-two matrix [m0 m1 m2 m3] to theusercoordinatesystem,andthentranslateby tx unitsin the Ü directionandty unitsin the Ý direction.

fconcat is a wrapperaroundthe morefundamentalfsetmatrix function. Thefollowing threefunctions(frotate , fscale , ftranslate )areconveniencefunc-tionsthatarespecialcasesof fconcat .

int frotate (doubletheta);Modify the transformationmatrix from userspaceto NDC spaceby pre-multiplyingit by thematrix [cos(theta) sin(theta) Þ sin(theta) cos(theta) 0 0]. Equivalently, rotatetheusercoordinatesystemaxesabouttheir origin by thetadegreescounterclockwise,with respectto their formerorientation.Thepositionof theusercoordinateorigin andthesizeof the Ü and Ý unitsremainunchanged.

int fscale (doublesx, doublesy);Modify the transformationmatrix from userspaceto NDC spaceby pre-multiplyingit by the matrix [sx 0 0 sy 0 0]. Equivalently, make the Ü and Ý units in the usercoordinatesystembethesizeof sx andsy unitsin theformerusercoordinatesystem.The positionof the usercoordinateorigin andthe orientationof the coordinateaxesareunchanged.

Page 132: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 127

int ftranslate (doubletx, doublety);Modify the transformationmatrix from userspaceto NDC spaceby pre-multiplyingit by thematrix [0 0 0 0 tx ty]. Equivalently, move theorigin of theusercoordinatesystemby tx units in the ß direction and ty units in the à direction, relative to theformerusercoordinatesystem.Thesizeof the ß and à unitsandtheorientationof thecoordinateaxesareunchanged.

9.5 Plotterparameters

In designingthe libplot library, every effort wasmadeto make the Plotter interfaceinde-pendentof thetypeof Plotter. To theextent thatPlottersdisplayindividual (i.e., instance-specific)behavior, thatbehavior is capturedby amanageablenumberof Plotterparameters. Eachparameterhasa valuethat is allowedto bea genericpointer(avoid * ). For mostparameters,thevalueis astring(achar * ).

Theparametervaluesof any Plotterareconstantoverthelifetime of thePlotter, andarespecifiedwhen the Plotter is created. In the C binding, avalue for any parameteris specifiedby callingthepl_setplparam function. Thepl_setplparam functionactsonaplPlotterParam sobject,whichencapsulatesPlotterparameters.WhenaPlotteris createdby callingpl_newpl_r ,apointerto aplPlotterParams objectis passedasthefinal argument.

If at Plotter creationtime a parameteris not specified,its default value will be used,unlessthe parameteris string-valuedand thereis an environmentvariableof the samename,in whichcasethe valueof that environmentvariablewill be used. This rule increasesrun-timeflexibility:anapplicationprogrammermayallow non-criticalPlotterparametersto bespecifiedby theuserviaenvironmentvariables.

In the C++ binding, the PlotterParams classand PlotterParams: :s et plp ar am,amemberfunction,aretheanaloguesof theplPlotterParam s datatypeandthefunctionpl_setplparam .

Thefollowingarethecurrently recognizedparameters(unrecognizedonesareignored). ThemostimportantonesareDISPLAY, which affectsX Plotters, BITMAPSIZE , which affectsX Plotters,PNG Plotters,PNM Plotters,andGIF Plotters,PAGESIZE, which affects Illustrator, Postscript,CGM, Fig, andHP-GLPlotters,andROTATION, whichaffectsall PlottersexceptMetafilePlotters.Thesefourparametersarelistedfirstandtheothersalphabetically. Mostof theremainingparameters,suchastheseveralwhosenamesbegin with " HPGL" , affectonly asingletypeof Plotter.

DISPLAY (Default NULL.) TheX Window Systemdisplayon which thegraphicsdisplaywillbepoppedup, asanX window. This is relevantonly to X Plotters.

BITMAPSIZE(Default " 570x570" .) The sizeof the graphicsdisplay(i.e., the viewport) in termsof pixels. This is relevant only to X Plotters, PNG Plotters,PNM Plotters,andGIFPlotters.ForX Plotters, thevalueof thisparameterwill automatically, if it is notset,betakenfrom theX resourceXplot.geometry . Thatis for backwardcompatibility.

X Plotters support precisepositioning of the graphicsdisplay. For example, ifBITMAPSIZE is " 570x570+0+0" then it will be positionedin the upper left cor-nerof theX Window Systemdisplay.

Page 133: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 128

PAGESIZE(Default " letter" .) Thepagetype,which determinesthesizeof thegraphicsdisplay(i.e., the viewport) usedby the Plotter. This is relevant only to SVG, Illustrator,Postscript,CGM, Fig, PCL, andHP-GL Plotters. " letter" meansan 8.5in by 11inpage.Any ISO pagesizein the range" a0" . . . " a4" or ANSI pagesizein the range" a" . . . " e" may be specified(" letter" is an aliasfor " a" and " tabloid" is an aliasfor " b" ). " legal" , " ledger" , and" b5" arerecognizedpagesizesalso.

For Illustrator, Postscript,PCLandFigPlotters,thegraphicsdisplaywill be,bydefault,asquareregioncenteredon thespecifiedpage.(For example,it will beacentered8insquareif PAGESIZEis " letter" .) For HP-GLPlotters,it will beasquareregionof thesamesize,but will notby defaultbecentered.SVG formatandWebCGMformathavenonotionof theWebpageonwhichthegraphicsdisplaywill ultimatelybepositioned.They do have anotionof default displaysize,thoughthiswill normallybeoverriddenwhentheSVG or WebCGMfile is placedonaWebpage.For thedefault displaysize,SVG andCGM Plotterswill usethegraphicsdisplaysizethatis usedby otherPlotters.

For the default size and location of the graphicsdisplay for eachpagetype, seeAppendix C [Page and Viewport Sizes], page156. You do not needto use thedefault graphicsdisplay, since either or both of its dimensionscan be specifiedexplicitly. For example, PAGESIZE could be specifiedas " letter,xsize=4in" , or" a4,xsize=10cm,ysize=15cm" . Thedimensionsareallowedto benegative(anegativedimensionresultsin a reflection).

For Plottersother thanSVG andCGM Plotters,the positionof the graphicsdisplayon the page,relative to its default position, can be adjustedby specifyingan off-set vector. For example, PAGESIZE could be specifiedas " letter,yoffset=1.2in" ,or " a4,xoffset=á 5mm,yoffset=2.0cm" . Inches,centimeters,andmillimetersarethesupportedunits.

It is also possible to position the graphics display precisely, by specifying thelocation of its lower left corner relative to the lower left cornerof the page. Forexample, PAGESIZE could be specified as " letter,xorigin=2in,yorigin=3in" , or" a4,xorigin=0.5cm,yorigin=0.5cm" . The precedingoptions may be intermingled.SVG and WebCGM Plotters ignore the " xoffset" , " yoffset" , " xorigin" , and" yorigin" options,sinceSVG format and WebCGM format have no notion of theWebpageon which thegraphicsdisplaywill ultimatelybepositioned.

ROTATION(Default " 0" .) Relevant to all Plottersother thanMetafile Plotters,which have nooutputdevice. Theangle,in degrees,by whichthegraphicsdisplay(i.e., theviewport)shouldberotated,relative to its defaultorientation.Recognizedvaluesare" 0" , " 90" ," 180" , and" 270" ; " no" and" yes" areequivalentto " 0" and" 90" respectively. Therotationis counterclockwise.

A rotatedviewportdoesnotchangethepositionof its fourcorners.Rather, thegraphicsarerotatedwithin it. If theviewport is rectangularratherthansquare,this ‘rotation’necessarilyincludesa rescaling.

This parameteris useful for switching betweenportrait and landscapeorientations.Internally, it determinestheaffine transformationfrom NDC (normalizeddevicecoor-dinate)spaceto device space.

Page 134: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 129

BG_COLOR(Default" white" .) Theinitial backgroundcolorof thegraphicsdisplay, whendrawingeachpageof graphics. This is relevant to X Plotters, PNG Plotters,PNM Plot-ters, GIF Plotters, CGM Plotters, ReGIS Plotters, and Metafile Plotters; also toX DrawablePlotters(for the last, the backgroundcolor shows up only if erase isinvoked). For informationonwhatcolornamesarerecognized,seeAppendixB [ColorNames],page155. Thebackgroundcolormaybechangedatany latertimeby invokingthebgcolor (or bgcolorname ) anderase operations.

SVG PlottersandCGM Plotterssupport" none" asa valuefor thebackgroundcolor.It will turnoff thebackground:thedrawn objectswill notbebackedby anything. Thisis usefulwhenthegeneratedSVG or WebCGMfile is to beplacedon aWebpage.

CGM_ENCODING(Default " binary" .) Relevantonly to CGM Plotters. " binary" meansthat theCGMoutput shoulduse the binary encoding. " clear text" meansthat the CGM outputshoulduseahuman-readableencoding.TheWebCGMprofile requiresthatthebinaryencodingbeused,but many CGM viewersandinterpreterscanalsoparsethecleartextencoding.Thethird standardCGM encoding," character" , is notcurrentlysupported.

CGM_MAX_VERSION(Default" 4" .) Relevantonly to CGM Plotters.An upperboundontheversionnumberof CGMformatthatisproduced.Many olderCGMinterpretersandviewers,suchastheonesbuilt into MicrosoftOfficeandothercommercialsoftware,only supportversion1CGM files. For fully adequatehandlingof fontsandline styles,version3 is necessary.By default, thepresentreleaseof libplot producesversion3 CGM files,i.e., it doesnotuseversion4 features.

EMULATE_COLOR(Default " no" .) Relevant to all Plotters. " yes" meansthat eachcolor in the outputshouldbereplacedby anappropriateshadeof gray. Thewell known formulafor CIEluminance,namely0 â 212671ã +0 â 715160ä +0 â 072169å , is used.

Thisparameteris seldomuseful,exceptwhenusingaPCLPlotterto prepareoutputforamonochromePCL 5device. Many monochromePCL 5devices,suchasmonochromeLaserJets,doapoorjob of emulatingcolorontheirown. They usuallymapHP-GL/2’ssevenstandardpencolors,includingevenyellow, to black.

GIF_ANIMATION(Default" yes" .) RelevantonlytoGIFPlotters." yes" meansthattheerase operationwill have specialsemantics:with theexceptionof its first invocation,it will actasaseparatorbetweensuccessive imagesin thewritten-outpseudo-GIFfile. " no" meansthat erase shouldact asit doeson otherPlottersthat do not write graphicsin realtime,i.e., it shoulderasetheimageunderconstructionby filling it with thebackgroundcolor. If " no" is specified,thepseudo-GIFfile will containonly asingleimage.

GIF_DELAY(Default " 0" .) Relevantonly to GIF Plotters.Thedelay, in hundredthsof a second,after eachimagein a written-outanimatedpseudo-GIFfile. The valueshouldbe anintegerin therange" 0" . . . " 65535" .

Page 135: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 130

GIF_ITERATIONS(Default " 0" .) Relevantonly to GIF Plotters.Thenumberof timesthatananimatedpseudo-GIFfile shouldbe ‘looped’. The value shouldbe an integer in the range" 0" . . . " 65535" .

HPGL_ASSIGN_COLORS(Default " no" .) Relevant only to HP-GL Plotters,andonly if the valueof HPGL_VERSIONis " 2" . " no" meansto draw with a fixedsetof pens,specifiedby settingthe HPGL_PENSparameter. " yes" meansthat pencolorswill not restrictedto thepalettespecifiedin HPGL_PENS: colorswill beassignedto “logical pens”in therange#1. . .#31, asneeded. Otherthancolor LaserJetprintersandDesignJetplotters,notmany HP-GL/2devicesallow theassignmentof colorsto logical pens. In particular,HP-GL/2penplottersdonot. Sothisparametershouldbeusedwith caution.

HPGL_OPAQUE_MODE(Default " yes" .) Relevant only to HP-GL Plotters,andonly if the valueof HPGL_VERSIONis " 2" . " yes" meansthat theHP-GL/2outputdevice shouldbeswitchedinto opaquemode,ratherthantransparentmode.This allows objectsto befilled withopaquewhite and other opaquecolors. It also allows the drawing of visible whitelines,which by conventionaredrawn with pen#0. Not all HP-GL/2devicessupportopaquemodeor theuseof pen#0 to draw visible white lines. In particular, HP-GL/2penplottersdo not. SomeolderHP-GL/2devicesreportedlymalfunctionif asked toswitch into opaquemode. If the outputof an HP-GL Plotter is to be sentto suchadevice,a " no" valueis recommended.

HPGL_PENS(Default " 1=black:2=red:3=green:4=yellow:5=blue:6=magenta:7=cyan" if the valueof HPGL_VERSIONis " 1.5" or " 2" and" 1=black" if thevalueof HPGL_VERSIONis " 1" . Relevantonly to HP-GLPlotters.Thesetof availablepens;theformatshouldbe self-explanatory. The color for any penin the range#1. . .#31 may be specified.For informationonwhatcolornamesarerecognized,seeAppendixB [Color Names],page155. Pen#1 mustalwaysbepresent,thoughit neednotbeblack. Any otherpenin therange#1. . .#31maybeomitted.

HPGL_ROTATE(Default " 0" .) Relevantonly to HP-GL Plotters.Theangle,in degrees,by which thegraphicsdisplay(i.e.,theviewport)shouldberotatedonthepagerelative to thedefaultorientation.Recognizedvaluesare" 0" , " 90" , " 180" , and" 270" ; " no" and" yes"areequivalentto " 0" and" 90" respectively. " 180" and" 270" aresupportedonly ifHPGL_VERSIONis " 2" .

Therotationrequestedby HPGL_ROTATEis differentfrom thesort requestedby theROTATIONparameter. ROTATIONrotatesthegraphicsdisplayin place, but HPGL_ROTATEboth rotatesthe graphicsdisplay and moves its lower left corner towardanothercornerof thepage.Altering theplottingareain suchawayis supportedby theHP-GL language.

The HPGL_ROTATEparameterfacilitatesswitchingbetweenportrait and landscapeorientations. For HP-GL devices that is frequentlya concern,sincesomeHP-GLdevices(“plotters”) draw with adefault landscapeorientation,while others(“printers”)

Page 136: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 131

draw with adefault portraitorientation.Thereis noprogrammaticwayof determiningwhich is which.

HPGL_VERSION(Default " 2" .) Relevant only to HP-GL Plotters. " 1" meansthat the outputshouldbegenericHP-GL, " 1.5" meansthat theoutputshouldbesuitablefor theHP7550Agraphicsplotter andthe HP758x,HP7595AandHP7596Adrafting plotters(HP-GLwith someHP-GL/2extensions),and" 2" meansthattheoutputshouldbemodernHP-GL/2. If theversionis lessthan" 2" thentheonly availablefontswill bevectorfonts,andall pathswill be drawn with a default thickness,so that invoking linewidth ,capmod, joinmod , and fmiterlimit will have no effect. Also, the ‘nonzerowindingnumberrule’ will notbesupportedwhenfilling paths,soinvoking fillmodwill havenoeffect. Additionally, if theversionis " 1" thenthefilling of arbitrarypathswill not besupported(circlesandrectanglesalignedwith thecoordinateaxesmaybefilled, however).

INTERLACE(Default " no" .) Relevant only to PNG and GIF Plotters. If the value is " yes" ,the output file will be interlaced. That meansit will be displayedin an interlaced(nonlinear)wayby many applications.

MAX_LINE_LENGTH(Default " 500" .) The maximumnumberof defining points that a path may have,beforeit is flushedto theoutputdevice. If this flushingoccurs,thepathwill besplitinto two or moresub-paths,thoughthe splitting shouldnot be noticeable. Splittingwill notbeperformedif thepathis to befilled.

This parameteris relevant to all PlottersexceptTektronixandMetafilePlotters.Thereasonfor splitting longpathsis thatsomedisplaydevices(e.g.,old PostscriptprintersandHP-GL penplotters)have limited buffer sizes. It is not relevant to Tektronix orMetafilePlotters,sincethey draw pathsin realtimeandhave no buffer limitations.

META_PORTABLE(Default " no" .) Relevant only to Metafile Plotters. " yes" meansthat the outputmetafileshouldusea portable(human-readable)encodingof graphics,ratherthanthedefault (binary)encoding.SeeAppendixD [Metafiles],page158.

PCL_ASSIGN_COLORS(Default " no" .) Relevantonly to PCL Plotters." no" meansto draw with a fixedsetof pens. " yes" meansthat pencolorswill not restrictedto this palette: colorswillbeassignedto “logical pens”,asneeded. OtherthancolorLaserJetprinters,notmanyPCL5 devicesallow theassignmentof colorsto logicalpens.Sothisparametershouldbeusedwith caution.

PCL_BEZIERS(Default " yes" .) Relevant only to PCL Plotters. " yes" meansthat when drawingBeziercurves,thespecial‘Bezierinstructions’will beused." no" meansthatthesein-structionswill notbeused.Instead,eachBeziercurvewill beapproximatedanddrawnasa polygonalline. Other thanthe LaserJetIII, which wasHewlett–Packard’s firstPCL5 printer, all Hewlett–Packard’s PCL 5 printerssupporttheBezierinstructions.

Page 137: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 132

PNM_PORTABLE(Default " no" .) Relevantonly to PNM Plotters." yes" meansthat theoutputshouldbe in a portable(human-readable)versionof PBM/PGM/PPMformat, rather thanthe default (binary) version. ‘Portable’ is somethingof a misnomer, since binaryPBM/PGM/PPMfilesarealsoportable,in thesensethatthey aremachine-independent.

TERM (DefaultNULL.) Relevantonly to TektronixPlotters.If thevalueis astringbeginningwith " xterm" , " nxterm" , or " kterm" , it is takenasa signthatthecurrentapplicationis runningin anX Window SystemVT100terminalemulator:anxterm , nxterm , orkterm . Beforedrawinggraphics,aTektronixPlotterwill emitanescapesequencethatcausestheterminalemulator’s auxiliaryTektronixwindow, which is normallyhidden,to popup. After thegraphicsaredrawn, anescapesequencethatreturnscontrolto theoriginal VT100 window will be emitted. The Tektronix window will remainon thescreen.

If thevalueis astringbeginningwith " kermit" , " ansi.sys" , or " nansi.sys" , it is takenasasignthatthecurrentapplicationisrunningin theVT100terminalemulatorprovidedby the MS-DOSversionof kermit . Beforedrawing graphics,a Tektronix Plotterwill emit anescapesequencethatswitchesthe terminalemulatorto Tektronixmode.Also, someof the Tektronix control codesemittedby the Plotterwill be kermit -specific. Therewill be a limited amountof color support,which is not normally thecase(the 16 ansi.sys colorswill be supported). The " dotdotdashed" line stylewill be supported,which is alsonot normally the case. After drawing graphics,thePlotterwill emitanescapesequencethatreturnstheemulatorto VT100mode.Thekeysequence‘ALT minus’ maybeemployedmanuallywithin kermit to switchbetweenthetwo modes.

TRANSPARENT_COLOR(Default " none" .) Relevantonly to PNGandGIF Plotters.If thevalueis arecognizedcolor name,thatcolor, if it appearsin theoutputfile, will betreatedastransparentbymostapplications.For informationon what namesarerecognized,seeAppendixB[Color Names],page155.

If TRANSPARENT_COLORis setandan animatedpseudo-GIFfile is produced,the‘restore to background’disposalmethodwill be usedfor eachimage in the file.Otherwise,the‘unspecified’disposalmethodwill beused.

USE_DOUBLE_BUFFERIN G(Default " no" .) Relevantonly to X PlottersandX DrawablePlotters. If thevalueis" yes" , adoublebufferingschemewill beusedwhendrawing graphics.Eachframeofgraphics,within a openpl . . .closepl pair, will bewritten to anoff-screenbufferratherthanto thePlotter’s display. Whenerase is invoked to enda frame,or whenclosepl is invoked,thecontentsof theoff-screenbufferwill becopiedto thePlotter’sdisplay, pixel by pixel. If successive framesdiffer only slightly, this will createtheillusion of smoothanimation.

SomeX displaysprovidespecialhardwaresupportfor doublebuffering. If thissupportis available, the X Plotterwill detectits presence,andwill draw graphicsusing theappropriateextensionto the X11 protocol (either DBE or MBX). In this casetheanimationwill besignificantlyfaster;on high-endgraphicshardware,at least.

Page 138: plotutils

Chapter9: libplot , a2-D VectorGraphicsLibrary 133

VANISH_ON_DELETE(Default " no" .) Relevantonly to X Plotters. If thevalueis " yes" , whena Plotterisdeleted,the window or windows that it haspoppedup will vanish. Otherwise,eachsuchwindow will remainon thescreenuntil it is removedby theuser(by typing ‘q’in it, or by clicking with amouse).

XDRAWABLE_COLORMAP(Default NULL.) Relevant only to X DrawablePlotters. If the value is non-NULL,it shouldbe a Colormap * , a pointer to a colormapfrom which colors shouldbeallocated.NULL indicatesthatthecolormapto beusedshouldbethedefaultcolormapof thedefault screenof theX display.

XDRAWABLE_DISPLAY(Default NULL.) Relevant only to X Drawable Plotters. The value should be aDisplay * , apointerto theX displaywith which thedrawable(s)to bedrawn in areassociated.

XDRAWABLE_DRAWABLE1XDRAWABLE_DRAWABLE2

(Default NULL.) Relevant only to X DrawablePlotters. If set,thevalueof eachoftheseparametersshouldbe a Drawable * , a pointer to a drawableto be drawn in.A ‘drawable’ is eithera window or a pixmap. At the time an X DrawablePlotter iscreated,at leastoneof thetwo parametersmustbeset.

X Drawable Plotterssupportsimultaneousdrawing in two drawablesbecauseit isoften useful to be able to draw graphicssimultaneouslyin both an X window andits backgroundpixmap. If two drawablesare specified,they must have the samedimensionsanddepth,andbeassociatedwith thesamescreenof theX display.

XDRAWABLE_VISUAL(Default NULL.) Relevant only to X DrawablePlotters. If set, the value shouldbe a Visual * , apointer to the ‘visual’ with which the colormap(seeabove) isassociated.Settingthisparameteris notrequired,but it is recommendedthatit besetifXDRAWABLE_COLORMAP is set.Undersomecircumstances,thatwill speedupcolorcell allocation.

X_AUTO_FLUSH(Default " yes" .) Relevant only to X Plotters. If the value is " yes" , an XFlushoperationis performedafter eachdrawing operation. That ensuresthat graphicsareflushedto theX Window Systemdisplay, andarevisible to theuser, immediatelyafterthey aredrawn. However, it slows down renderingconsiderably. If thevalueis " no" ,drawing is faster, sinceit doesnot take placein realtime.

Page 139: plotutils

AppendixA: Fonts,Strings,andSymbols 134

Appendix A Fonts, Strings, and Symbols

The GNU libplot graphicslibrary and applicationsbuilt on it, such as graph , plot ,pic2plot , tek2plot , andplotfont , candraw text stringsin a wide variety of fonts. Textstringsmayincludecharactersfrom morethanonefont in atypeface,andmayincludesuperscripts,subscripts,andsquareroots. A wide varietyof marker symbolscanalsobedrawn. Thefollowingsectionsexplainhow to usethesefeatures.

A.1 Available text fonts

The GNU libplot library andapplicationsbuilt on it, suchasgraph , plot , pic2plot ,tek2plot , and plotfont , can usemany fonts. Theseinclude 22 Hershey vector fonts, 35Postscriptfonts,45PCL5 fonts,and18Hewlett–Packardvectorfonts. Wecall these120supportedfonts the ‘built-in’ fonts. The Hershey fonts are constructedfrom stroked charactersdigitizedc. 1967by Dr. Allen V. Hershey at theU.S.Naval SurfaceWeaponsCenterin Dahlgren,VA. The35Postscriptfontsaretheoutlinefontsresidentin all modernPostscriptprinters,andthe45PCL 5fontsaretheoutline fonts residentin modernHewlett–PackardLaserJetprintersandplotters. (OfthePCL5 fonts, theold LaserJetIII, which wasHewlett–Packard’s first PCL 5 printer, supportedonly eight: theUniversandCGTimesfonts.) The 18 Hewlett–Packardvectorfonts arefonts thatareresidentin Hewlett–Packardprintersandplotters(mostlythelatter).

TheHershey fontscanbeusedby all typesof Plottersupportedby libplot , andthePostscriptfontscanbeusedby X, SVG, Illustrator, Postscript,andFig Plotters.So,for example,all variantsof graph canusetheHershey fonts,andgraph -T X, graph -T svg , graph -T ai , graph-T ps , graph -T cgm andgraph -T fig canusethePostscriptfonts. ThePCL5 fontscanbeusedby by SVG, Illustrator, PCL, andHP-GL Plotters,andby graph -T svg , graph -T ai ,graph -T pcl , andgraph -T hpgl . TheHewlett–Packardvectorfontscanbeusedby PCLandHP-GL Plotters,andby graph -T pcl andgraph -T hpgl . X Plottersandgraph -T X arenotrestrictedto thebuilt-in Hershey andPostscriptfonts. They canuseany X Window Systemfont.

The plotfont utility, which acceptsthe ‘ -T ’ option, will print a charactermapof any fontthatis availablein thespecifiedoutputformat. SeeChapter6 [plotfont], page51.

For thepurposeof plottingtext strings(seeSectionA.4 [Text StringFormat],page141),the120built-in fontsaredividedinto typefaces.As you canseefrom thefollowing tables,our conventionis that in any typefacewith morethana singlefont, font #1 is thenormalfont, font #2 is italic oroblique,font #3 is bold, andfont #4 is bold italic or bold oblique. Additional variants(if any) arenumbered#5 andhigher.

The22Hershey fontsaredividedinto typefacesasfollows.æ HersheySerif

1. HersheySerif

2. HersheySerif-Italic

3. HersheySerif-Bold

4. HersheySerif-BoldItalic

5. HersheyCyrillic

6. HersheyCyrillic-Oblique

7. HersheyEUC

Page 140: plotutils

AppendixA: Fonts,Strings,andSymbols 135

ç HersheySans

1. HersheySans

2. HersheySans-Oblique

3. HersheySans-Bold

4. HersheySans-BoldObliqueç HersheyScript

1. HersheyScript

2. HersheyScript

3. HersheyScript-Bold

4. HersheyScript-Boldç HersheyGothicEnglishç HersheyGothicGermanç HersheyGothicItalianç HersheySerifSymbol

1. HersheySerifSymbol

2. HersheySerifSymbol-Oblique

3. HersheySerifSymbol-Bold

4. HersheySerifSymbol-BoldObliqueç HersheySansSymbol

1. HersheySansSymbol

2. HersheySansSymbol-Oblique

Nearlyall Hershey fontsexcepttheSymbolfontsusetheISO-Latin-1encoding,which is asupersetof ASCII. The Symbolfonts consistof Greekcharactersandmathematicalsymbols,andusethesymbolfont encodingdocumentedin thePostscriptLanguageReferenceManual. By convention,eachHershey typefacecontainsa symbol font (HersheySerifSymbolor HersheySansSymbol,asappropriate)asfont #0.

HersheyCyrillic, HersheyCyrillic-Oblique, andHersheyEUC (which is a Japanesefont) aretheonly non-SymbolHershey fontsthatdo notusetheISO-Latin-1encoding.For their encodings,seeSectionA.2 [Cyrillic andJapanese],page139.

The35Postscriptfontsaredividedinto typefacesasfollows.ç Helvetica

1. Helvetica

2. Helvetica-Oblique

3. Helvetica-Bold

4. Helvetica-BoldObliqueç Helvetica-Narrow

1. Helvetica-Narrow

2. Helvetica-Narrow-Oblique

3. Helvetica-Narrow-Bold

Page 141: plotutils

AppendixA: Fonts,Strings,andSymbols 136

4. Helvetica-Narrow-BoldObliqueè Times

1. Times-Roman

2. Times-Italic

3. Times-Bold

4. Times-BoldItalicè AvantGarde

1. AvantGarde-Book

2. AvantGarde-BookOblique

3. AvantGarde-Demi

4. AvantGarde-DemiObliqueè Bookman

1. Bookman-Light

2. Bookman-LightItalic

3. Bookman-Demi

4. Bookman-DemiItalicè Courier

1. Courier

2. Courier-Oblique

3. Courier-Bold

4. Courier-BoldObliqueè NewCenturySchlbk

1. NewCenturySchlbk-Roman

2. NewCenturySchlbk-Italic

3. NewCenturySchlbk-Bold

4. NewCenturySchlbk-BoldItalicè Palatino

1. Palatino-Roman

2. Palatino-Italic

3. Palatino-Bold

4. Palatino-BoldItalicè ZapfChancery-MediumItalicè ZapfDingbatsè Symbol

All PostscriptfontsexcepttheZapfDingbatsandSymbolfontsusetheISO-Latin-1encoding.Theencodingsusedby theZapfDingbatsandSymbolfontsaredocumentedin thePostscriptLanguageReferenceManual. By convention,eachPostscripttypefacecontainstheSymbolfont asfont #0.

The45PCL 5 fontsaredividedinto typefacesasfollows.è Univers

Page 142: plotutils

AppendixA: Fonts,Strings,andSymbols 137

1. Univers

2. Univers-Oblique

3. Univers-Bold

4. Univers-BoldObliqueé UniversCondensed

1. UniversCondensed

2. UniversCondensed-Oblique

3. UniversCondensed-Bold

4. UniversCondensed-BoldObliqueé CGTimes

1. CGTimes-Roman

2. CGTimes-Italic

3. CGTimes-Bold

4. CGTimes-BoldItalicé Albertus

1. AlbertusMedium

2. AlbertusMedium

3. AlbertusExtraBold

4. AlbertusExtraBoldé AntiqueOlive

1. AntiqueOlive

2. AntiqueOlive-Italic

3. AntiqueOlive-Boldé Arial

1. Arial-Roman

2. Arial-Italic

3. Arial-Bold

4. Arial-BoldItalicé ClarendonCondensedé Coroneté Courier

1. Courier

2. Courier-Italic

3. Courier-Bold

4. Courier-BoldItalicé Garamond

1. Garamond

2. Garamond-Italic

3. Garamond-Bold

Page 143: plotutils

AppendixA: Fonts,Strings,andSymbols 138

4. Garamond-BoldItalicê LetterGothic

1. LetterGothic-Roman

2. LetterGothic-Italic

3. LetterGothic-Bold

4. LetterGothic-BoldItalicê Marigoldê CGOmega

1. CGOmega-Roman

2. CGOmega-Italic

3. CGOmega-Bold

4. CGOmega-BoldItalicê TimesNewRoman

1. TimesNewRoman

2. TimesNewRoman-Italic

3. TimesNewRoman-Bold

4. TimesNewRoman-BoldItalicê Wingdingsê Symbol

All PCL 5 fonts except the Wingdings and Symbol fonts use the ISO-Latin-1 encoding. Theencodingusedby the Symbol font is the symbol font encodingdocumentedin the PostscriptLanguageReferenceManual. By convention, eachPCL typeface containsthe Symbol font asfont #0.

The18Hewlett–Packardvectorfontsaredividedinto typefacesasfollows.ê Arc

1. Arc

2. Arc-Oblique

3. Arc-Bold

4. Arc-BoldObliqueê Stick

1. Stick

2. Stick-Oblique

3. Stick-Bold

4. Stick-BoldObliqueê ArcANK

1. ArcANK*

2. ArcANK-Oblique*

3. ArcANK-Bold*

4. ArcANK-BoldOblique*

Page 144: plotutils

AppendixA: Fonts,Strings,andSymbols 139

ë StickANK

1. StickANK*

2. StickANK-Oblique*

3. StickANK-Bold*

4. StickANK-BoldOblique*ë ArcSymbol*ë StickSymbol*

TheHewlett–Packardvectorfontswith anasterisk(theANK andSymbolfonts)areonly availablewhenproducingHP-GL/2graphics,or HP-GL graphicsfor theHP7550AgraphicsplotterandtheHP758x,HP7595Aand HP7596Adrafting plotters. That is, they are available only if HPGL_VERSION is " 2" (the default) or " 1.5" . The ANK fonts are Japanesefonts (seeSectionA.2[Cyrillic andJapanese],page139),andtheSymbolfontscontainafew miscellaneousmathematicalsymbols.

All Hewlett–PackardvectorfontsexcepttheANK andSymbolfontsusetheISO-Latin-1encod-ing. TheArc fontsareproportional(variable-width)fonts,andtheStick fontsarefixed-widthfonts.If HP-GL/2or HP-GLoutputis selected,theArc fontsareassumedto bekernedvia device-residentkerning tables. But whenproducingPCL5 output, it is assumedthat the displaydevice will dono kerning. ApparentlyHewlett–Packarddroppedsupportfor device-residentkerningtableswhenemulatingHP-GL/2 from within PCL5. For informationaboutHewlett–Packardvectorfontsandthewayin whichthey arekerned(in HP-GLpenplotters,at least), seethearticlebyL. W. Hennesseeetal. in theNov. 1981issueof theHewlett–PackardJournal.

To whatextentdo thefontssupportedby libplot containligatures?ThePostscriptfonts,thePCL5 fonts, andthe Hewlett–Packardvectorfonts, at leastasimplementedin libplot , do notcontainligatures. However, six of the 22 Hershey fonts containligatures. The charactercom-binations" fi" , " ff" , " fl" , " ffi" , and " ffl" areautomaticallydrawn as ligaturesin HersheySerifandHersheySerif-Italic. (Also in the two HersheyCyrillic fonts andHersheyEUC, sinceinsofarasprintableASCII charactersareconcerned,they are identical [or almostidentical] to Hershey-Serif.) In addition, " tz" and" ch" areligaturesin HersheyGothicGerman.TheGermandouble-scharacter‘ß’ , which is calledan‘eszet’, is not treatedasa ligaturein any font. To obtainaneszet,youmusteitherrequestonewith theescapesequence"\ ss" (seeSectionA.4 [Text StringFormat],page141),or, if youhave an8-bit keyboard,typeaneszetexplicitly.

A.2 Cyrillic andJapanesefonts

Thebuilt-in fontsdiscussedin theprevious sectionincludeCyrillic andJapanesevectorfonts.This sectionexplainshow thesefontsareencoded,i.e., how their charactermapsarelaid out. Youmayusetheplotfont utility to displaythecharactermapfor any font, includingtheCyrillic andJapanesevectorfonts. SeeChapter6 [plotfont], page51.

TheHersheyCyrillic andHersheyCyrillic-Oblique fonts usean encodingcalledKOI8-R, a su-persetof ASCII that hasbecomethe defacto standardfor Unix and networking applicationsintheformerSoviet Union. Insofar asprintableASCII charactersgo, they resembletheHersheySerifvectorfont. But theirupperhalvesaredifferent.Thebyterange0xc0 . . .0xdf containslower-caseCyrillic charactersandthebyterange0xe0 . . .0xff containsuppercaseCyrillic characters.Addi-tionalCyrillic charactersarelocatedat0xa3 and0xb3 . For moreontheencodingscheme,seethe

Page 145: plotutils

AppendixA: Fonts,Strings,andSymbols 140

official KOI8-RWebpage(http://www.nagu al .pp .r u/ ˜a ch e/k oi 8. ht ml ) andInternetRFC1489,which is availablefrom theInformationSciencesInstitute(http://www.isi. edu).

The HersheyEUC font is a vector font that is usedfor displayingJapanesetext. It usesthe8-bit EUC-JPencoding. EUC standsfor ‘extendedUnix code’, which is a schemefor encodingJapanese,and also other charactersets(e.g., Greekand Cyrillic) as multibyte characterstrings.The formatof EUC stringsis explainedin KenLunde’s UnderstandingJapaneseInformationPro-cessing(O’Reilly, 1993),whichcontainsmuchadditionalinformationonJapanesetext processing.Seealsohison-linesupplement(http://www.ora. co m/peopl e/ auth or s/l unde/c jk _inf.html ), andhis morerecentbookCJKV InformationProcessing(O’Reilly, 1999).

In the HersheyEUC font, charactersin theprintableASCII range,0x20 . . .0x7e , aresimilarto HersheySerif (their encodingis ‘JIS Roman’, an ASCII variant standardizedby the JapaneseIndustrialStandardsCommittee).Also, eachsuccessive pair of bytesin the0xa1 . . .0xfe rangedefinesasinglecharacter intheJISX0208standard. Thecharactersin theJISX0208standardincludeJapanesesyllabic characters(Hiraganaand Katakana),ideographiccharacters(Kanji), Roman,Greek,andCyrillic alphabets,punctuationmarks,andmiscellaneoussymbols. For example,theJISX0208standardindexesthe83 Hiraganaas0x2421 . . .0x2473 . To obtaintheEUC codeforany JISX0208character, you would add0x80 to eachbyte (i.e., ‘set thehigh bit’ on eachbyte).Sothefirst of the83 Hiragana(0x2421 ) would beencodedasthesuccessive pair of bytes0xa4and0xa1 .

Theimplementationof theJISX0208standardin theHersheyEUCfont isbasedonDr. Hershey’sdigitizations,andis completeenoughto beuseful. All 83 Hiraganaand86 Katakanaareavailable,though the little-used ‘half-width Katakana’are not supported. Also, 603 Kanji are available,including 596 of the 2965JIS Level 1 (i.e., frequentlyused)Kanji. The Hiragana,the Katakana,andtheavailableKanji all have thesamewidth. Thefile ‘kanji.doc ’, which on mostsystemsis installedin ‘ /usr/share/libp lo t ’ or ‘ /usr/local/share /l ib pl ot ’, lists the 603available Kanji. EachJIS X0208 characterthat is unavailable will be drawn as an ‘undefinedcharacter’glyph (abundleof horizontallines).

TheeightHewlett–Packardvectorfonts in theArcANK andStickANK typefacesarealsousedfor displayingJapanesetext. They areavailablewhenproducingHP-GL/2output,or HP-GLoutputfor theHP7550AgraphicsplotterandtheHP758x,HP7595AandHP7596Adraftingplotters.Thatis, they areavailableonly if HPGL_VERSIONis " 2" (thedefault) or " 1.5" .

ANK standsfor Alphabet, Numerals,and Katakana. The ANK fonts use a specialmixedencoding.The lower half of eachfont usestheJIS Romanencoding,andtheupperhalf containshalf-width Katakana.Half-width KatakanaaresimplifiedKatakanathatmayneedto beequippedwith diacriticalmarks.Thediacriticalmarksareincludedin theencodingasseparatecharacters.

A.3 Available text fonts for the X Window System

The command-line graphics programs graph -T X, plot -T X, pic2plot -T X,tek2plot -T X, and plotfont -T X, and the libplot library that they are built on, candraw text on anX Window Systemdisplayin a wide varietyof fonts. This includesthe22 built-inHershey vectorfonts. They canusethe35 built-in Postscriptfonts too, if thosefontsareavailableon theX display. Most releasesof theplotting utilities includefreely distributableversionsof the35 Postscriptfonts,in Type1 format,thatareeasilyinstalledon any X display.

In fact, the plotting utilities can usemost fonts that are available on the currentX display.This includesall scalablefonts that have a so-calledXLFD (X Logical Font Description)name.

Page 146: plotutils

AppendixA: Fonts,Strings,andSymbols 141

For example,the" CharterBT-Roman" font is availableonmany X displays. It hasa formalXLFDname,namely" -bitstream-charter-medium-r-normal–0-0-0-0-p-0-iso8859-1" . Theplottingutilitieswould referto it as" charter-medium-r-normal" . Thecommand

echo 0 0 1 1 2 0 | graph -T X -F charter-medium- r- normal

woulddraw aplot in apopped-upX window, in whichall axisticks arelabeledin this font.

YoumaydeterminewhichfontsareavailableonanX displaybyusingthexlsfonts command.Fonts whosenamesend in " -0-0-0-0-p-0-iso8859-1" or " -0-0-0-0-m-0-iso8859-1" are scalableISO-Latin-1fonts that canbe usedby libplot ’s X Plottersandby theplotting utilities that arebuilt on libplot . The two sortsof font arevariable-widthandfixed-width fonts, respectively.Fontswhosenamesendin " iso8859-2" , etc., and " adobe-fontspecific" , may alsobe used,eventhoughthey do notemploy thestandardISO-Latin-1encoding.

The escapesequencesthat provide accessto the non-ASCII ‘8-bit’ charactersin the built-inISO-Latin-1fontsmaybeemployedwhenusingany ISO-Latin-1X Window Systemfont. For moreon escapesequences,seeSectionA.4 [Text StringFormat],page141. As anexample,"\ Po" willyield theBritish poundssterlingsymbol‘$’ . Thecommand

echo 0 0 1 1 | graph -T X -F charter-medium -r- normal -L "A \Po1 Plot"

shows how this symbolcouldbeusedin a graphlabel. In thesameway, theescapesequencesthatprovide accessto mathematicalsymbolsandGreekcharactersmay be employed whenusinganyX Window Systemfont, whetheror not it is anISO-Latin-1font.

The plotting utilities, including graph , supporta ‘ --bitmap-size ’ option. If the ‘ -T X’optionisused,it setsthesizeof thepopped-upX Window. Youmayuseit toobtainsomeinterestingvisualeffects. Eachof theplotting utilities assumesthat it is drawing in a squareregion, so if youusethe‘ --bitmap-size 800x400 ’ option,your plot will bescaledanisotropically, by a largerfactorin thehorizontaldirectionthanin theverticaldirection.Thefontsin theplot will bescaledinthesameway. Actually, this requiresa modern(X11R6)display. If your X displaycannotscaleafont, adefault scalablefont (suchas" HersheySerif" ) will besubstituted.

A.4 Text string format andescapesequences

Text stringsthataredrawn by theGNU libplot library andby applicationsbuilt on it, suchas graph , plot , pic2plot , tek2plot , and plotfont , must consistof printablecharac-ters. No embeddedcontrol characters,suchasnewlines or carriagereturns,areallowed. Techni-cally, a characteris ‘printable’ if it comesfrom eitherof the two byte ranges0x20 . . .0x7e and0xa0 . . .0xff . Theformeris theprintableASCII rangeandthelatteris theprintable‘8-bit’ range.

Text stringsmay, however, include embedded‘escapesequences’that shift the font, appendsubscriptsor superscripts,or include non-ASCII charactersand mathematicalsymbols. As aconsequence,theaxislabelsonaplot preparedwith graph mayincludesuchfeatures.Somaythetext stringsthatpic2plot usesto labelobjects.

The format of the escapesequencesshouldlook familiar to anyone who is familiar with theTEX, troff , or groff documentformatters.Eachescapesequenceconsistsof threecharacters:abackslashandtwoadditionalcharacters.Themostfrequentlyusedescapesequencesareasfollows.

"\ sp" startsuperscriptmode

"\ ep" endsuperscriptmode

"\ sb" startsubscriptmode

Page 147: plotutils

AppendixA: Fonts,Strings,andSymbols 142

"\ eb" endsubscriptmode

"\ mk" markposition

"\ rt" returnto markedposition

For example,thestring" x\ sp2\ ep" wouldbeinterpretedas‘x squared’.Subscriptson subscripts,etc., are allowed. Subscriptsandsuperscriptsmay be vertically alignedby judicioususeof the"\ mk" and"\ rt" escapesequences.For example," a\ mk\ sbi\ eb\ rt\ sp2\ ep" produces" asubisquared" , with theexponent‘2’ placedimmediatelyabove thesubscript.

Therearealsoescapesequencesthat switch from font to font within a typeface. For an enu-merationof the fonts within eachtypeface, seeSectionA.1 [Text Fonts], page134. Supposefor examplethat the currentfont is Times-Roman,which is font #1 in the ‘Times’ typeface. Thestring " A \ f2very\ f1 well labeledaxis" would be a string in which the word ‘very’ appearsinTimes-ItalicratherthanTimes-Roman.That is becauseTimes-Italicis the#2 font in thetypeface.Font-switchingescapesequencesareof the form "\ fn" , wheren is thenumberof the font to beswitchedto. For compatibility with troff andgroff , "\ fR" , "\ fI" , "\ fB" areequivalentto"\ f1" , "\ f2" , "\ f3" , respectively. "\ fP" will switch the font to thepreviously usedfont (onlyonefont is remembered).Thereis currentlyno supportfor switchingbetweenfonts in differenttypefaces.

Thereare also a few escapesequencesfor horizontalshifts, which are useful for improvinghorizontalalignment,suchas when shifting betweenitalic and non-italic fonts. "\ r1" , "\ r2" ,"\ r4" , "\ r6" , "\ r8" , and"\ rˆ" areescapesequencesthat shift right by 1 em,1/2 em,1/4 em,1/6 em,1/8 em,and1/12 em, respectively. "\ l1" , "\ l2" , "\ l4" , "\ l6" , "\ l8" , and"\ lˆ" aresimilar, but shift left insteadof right. " A \ fIvery\ rˆ\ fP well labeledaxis" would look slightlybetterthan" A \ fIvery\ fP well labeledaxis" .

Squarerootsarehandledwith the aid of a specialpair of escapesequences,togetherwith the"\ mk" and "\ rt" sequencesdiscussedabove. A squareroot symbol is begun with "\ sr" , andcontinuedarbitrarily far to theright with theoverbar(‘run’) escapesequence,"\ rn" . For example,thestring "\ sr\ mk\ rn\ rn\ rtab" would beplottedas‘the squareroot of ab’. To adjustthe lengthof theoverbar, youmayneedto experimentwith thenumberof times"\ rn" appears.

To underlinea string, you would use "\ ul" , the underlineescapesequence,one or moretimes. The "\ mk" . . . "\ rt" trick would be employed in the sameway. So, for example,"\ mk\ ul\ ul\ ul\ rtabc" would yield an underlined" abc" . To adjust the length of the under-line, you mayneedto experimentwith thenumberof times"\ ul" appears.You mayalsoneedtouseoneor moreof theabovementionedhorizontalshifts. For example, if the" HersheySerif" fontwereused,"\ mk\ ul\ ul\ l8\ ul\ rtabc" wouldyieldabetterunderlinethan"\ mk\ ul\ ul\ ul\ rtabc" .

Besidestheprecedingescapesequences,therearealsoescapesequencesfor theprintablenon-ASCII charactersin eachof the built-in ISO-Latin-1 fonts (which meansin every built-in font,except for the symbol fonts, the HersheyCyrillic fonts, HersheyEUC, and ZapfDingbats). Theusefulnon-ASCIIcharactersincludeaccentedcharactersamongothers.Such‘8-bit’ characters,inthe0xa0 . . .0xff byterange,maybeincludeddirectly in a text string. But if your terminaldoesnotpermitthis,youmayusetheescapesequencesfor theminstead.

Thereareescapesequencesfor themathematicalsymbolsandGreekcharactersin thesymbolfonts, aswell. This is how the symbolfonts areusuallyaccessed.Which symbolfont the math-ematicalsymbolsand Greekcharactersare taken from dependson whetheryour currentfont isa Hershey font or a non-Hershey font. They are taken from the HersheySerifSymbolfont or theHersheySansSymbolfont in theformercase,andfrom theSymbolfont in thelatter.

Page 148: plotutils

AppendixA: Fonts,Strings,andSymbols 143

Thefollowing aretheescapesequencesthatprovide accessto thenon-ASCIIcharactersof thecurrent font, provided that it is an ISO-Latin-1 font. Eachescapesequenceis followed by thepositionof thecorrespondingcharacterin the ISO-Latin-1encoding(in decimal),andthe officialPostscriptnameof thecharacter. Most namesshouldbeself-explanatory. For example, ‘eacute’isa lower-case‘e’, equippedwith anacuteaccent.

"\ r!" [161] exclamdown

"\ ct" [162] cent

"\ Po" [163] sterling

"\ Cs" [164] currency

"\ Ye" [165] yen

"\ bb" [166] brokenbar

"\ sc" [167] section

"\ ad" [168] dieresis

"\ co" [169] copyright

"\ Of" [170] ordfeminine

"\ Fo" [171] guillemotleft

"\ no" [172] logicalnot

"\ hy" [173] hyphen

"\ rg" [174] registered

"\ a-" [175] macron

"\ de" [176] degree

"\+ -" [177] plusminus

"\ S2" [178] twosuperior

"\ S3" [179] threesuperior

"\ aa" [180] acute

"\ *m" [181] mu

"\ ps" [182] paragraph

"\ md" [183] periodcentered

"\ ac" [184] cedilla

"\ S1" [185] onesuperior

"\ Om" [186] ordmasculine

"\ Fc" [187] guillemotright

"\ 14" [188] onequarter

"\ 12" [189] onehalf

Page 149: plotutils

AppendixA: Fonts,Strings,andSymbols 144

"\ 34" [190] threequarters

"\ r?" [191] questiondown

"\ ‘A" [192] Agrave

"\ ’A " [193] Aacute

"\ˆ A" [194] Acircumflex

"\˜ A" [195] Atilde

"\ :A" [196] Adieresis

"\ oA" [197] Aring

"\ AE" [198] AE

"\ ,C" [199] Ccedilla

"\ ‘E" [200] Egrave

"\ ’E" [201] Eacute

"\ˆ E" [202] Ecircumflex

"\ :E" [203] Edieresis

"\ ‘I " [204] Igrave

"\ ’I " [205] Iacute

"\ˆ I" [206] Icircumflex

"\ :I" [207] Idieresis

"\ -D" [208] Eth

"\˜ N" [209] Ntilde

"\ ’O" [210] Ograve

"\ ’O" [211] Oacute

"\ˆ O" [212] Ocircumflex

"\˜ O" [213] Otilde

"\ :O" [214] Odieresis

"\ mu" [215] multiply

"\ /O" [216] Oslash

"\ ‘U " [217] Ugrave

"\ ’U " [218] Uacute

"\ˆ U" [219] Ucircumflex

"\ :U" [220] Udieresis

"\ ’Y " [221] Yacute

"\ TP" [222] Thorn

Page 150: plotutils

AppendixA: Fonts,Strings,andSymbols 145

"\ ss" [223] germandbls

"\ ‘a" [224] agrave

"\ ’a" [225] aacute

"\ˆ a" [226] acircumflex

"\˜ a" [227] atilde

"\ :a" [228] adieresis

"\ oa" [229] aring

"\ ae" [230] ae

"\ ,c" [231] ccedilla

"\ ‘e" [232] egrave

"\ ’e" [233] eacute

"\ˆ e" [234] ecircumflex

"\ :e" [235] edieresis

"\ ‘i " [236] igrave

"\ ’i " [237] iacute

"\ˆ i" [238] icircumflex

"\ :i" [239] idieresis

"\ Sd" [240] eth

"\˜ n" [241] ntilde

"\ ‘o" [242] ograve

"\ ’o" [243] oacute

"\ˆ o" [244] ocircumflex

"\˜ o" [245] otilde

"\ :o" [246] odieresis

"\ di" [247] divide

"\ /o" [248] oslash

"\ ‘u" [249] ugrave

"\ ’u" [250] uacute

"\ˆ u" [251] ucircumflex

"\ :u" [252] udieresis

"\ ’y" [253] yacute

"\ Tp" [254] thorn

"\ :y" [255] ydieresis

Page 151: plotutils

AppendixA: Fonts,Strings,andSymbols 146

Thefollowing aretheescapesequencesthatprovideaccessto mathematicalsymbolsandGreekcharactersin the currentsymbol font, whetherHersheySerifSymbolor HersheySansSymbol(forHershey fonts)or Symbol(for Postscriptfonts). Eachescapesequenceis followedby theposition(in octal) of thecorrespondingcharacterin thesymbolencoding,andtheofficial Postscriptnameof thecharacter. Many escapesequencesandnamesshouldbeself-explanatory. "\ *a" representsa lower-caseGreekalpha,for example. For a tabledisplayingeachof thecharactersbelow, seethePostscriptLanguageReferenceManual.

"\ fa" [0042]universal

"\ te" [0044]existential

"\ st" [0047]suchthat

"\ ** " [0052]asteriskmath

"\ =˜" [0100]congruent

"\ *A " [0101]Alpha

"\ *B " [0102]Beta

"\ *X " [0103]Chi

"\ *D " [0104]Delta

"\ *E" [0105]Epsilon

"\ *F" [0106]Phi

"\ *G" [0107]Gamma

"\ *Y " [0110]Eta

"\ *I " [0111] Iota

"\+ h" [0112] theta1

"\ *K " [0113]Kappa

"\ *L " [0114]Lambda

"\ *M " [0115]Mu

"\ *N " [0116]Nu

"\ *O" [0117]Omicron

"\ *P" [0120]Pi

"\ *H " [0121]Theta

"\ *R" [0122]Rho

"\ *S" [0123]Sigma

"\ *T " [0124]Tau

"\ *U " [0125]Upsilon

"\ ts" [0126]sigma1

"\ *W " [0127]Omega

Page 152: plotutils

AppendixA: Fonts,Strings,andSymbols 147

"\ *C" [0130]Xi

"\ *Q" [0131]Psi

"\ *Z " [0132]Zeta

"\ tf" [0134] therefore

"\ pp" [0136]perpendicular

"\ ul" [0137]underline

"\ rx" [0140] radicalex

"\ *a" [0141]alpha

"\ *b" [0142]beta

"\ *x" [0143]chi

"\ *d" [0144]delta

"\ *e" [0145]epsilon

"\ *f " [0146]phi

"\ *g" [0147]gamma

"\ *y" [0150]eta

"\ *i " [0151] iota

"\+ f" [0152]phi1

"\ *k" [0153]kappa

"\ *l " [0154] lambda

"\ *m" [0155]mu

"\ *n" [0156]nu

"\ *o" [0157]omicron

"\ *p" [0160]pi

"\ *h" [0161] theta

"\ *r" [0162] rho

"\ *s" [0163]sigma

"\ *t" [0164] tau

"\ *u" [0165]upsilon

"\+ p" [0166]omega1

"\ *w " [0167]omega

"\ *c" [0170]xi

"\ *q" [0171]psi

"\ *z" [0172]zeta

Page 153: plotutils

AppendixA: Fonts,Strings,andSymbols 148

"\ ap" [0176]similar

"\+ U" [0241]Upsilon1

"\ fm" [0242]minute

"\< =" [0243] lessequal

"\ f/" [0244] fraction

"\ if" [0245] infinity

"\ Fn" [0246]florin

"\ CL" [0247]club

"\ DI" [0250]diamond

"\ HE" [0251]heart

"\ SP" [0252]spade

"\<>" [0253]arrowboth

"\< -" [0254]arrowleft

"\ ua" [0255]arrowup

"\ ->" [0256]arrowright

"\ da" [0257]arrowdown

"\ de" [0260]degree

"\+ -" [0261]plusminus

"\ sd" [0262]second

"\> =" [0263]greaterequal

"\ mu" [0264]multiply

"\ pt" [0265]proportional

"\ pd" [0266]partialdiff

"\ bu" [0267]bullet

"\ di" [0270]divide

"\ !=" [0271]notequal

"\ ==" [0272]equivalence

"\˜˜" [0273]approxequal

"\ .." [0274]ellipsis

NONE [0275]arrowvertex

"\ an" [0276]arrowhorizex

"\ CR" [0277]carriagereturn

"\ Ah" [0300]aleph

Page 154: plotutils

AppendixA: Fonts,Strings,andSymbols 149

"\ Im" [0301] Ifraktur

"\ Re" [0302]Rfraktur

"\ wp" [0303]weierstrass

"\ c*" [0304]circlemultiply

"\ c+" [0305]circleplus

"\ es" [0306]emptyset

"\ ca" [0307]cap

"\ cu" [0310]cup

"\ SS" [0311]superset

"\ ip" [0312] reflexsuperset

"\ n<" [0313]notsubset

"\ SB" [0314]subset

"\ ib" [0315] reflexsubset

"\ mo" [0316]element

"\ nm" [0317]notelement

"\ / " [0320]angle

"\ gr" [0321]nabla

"\ rg" [0322] registerserif

"\ co" [0323]copyrightserif

"\ tm" [0324] trademarkserif

"\ PR" [0325]product

"\ sr" [0326] radical

"\ md" [0327]dotmath

"\ no" [0330] logicalnot

"\ AN" [0331] logicaland

"\ OR" [0332] logicalor

"\ hA" [0333]arrowdblboth

"\ lA " [0334]arrowdblleft

"\ uA" [0335]arrowdblup

"\ rA" [0336]arrowdblright

"\ dA" [0337]arrowdbldown

"\ lz" [0340] lozenge

"\ la" [0341]angleleft

Page 155: plotutils

AppendixA: Fonts,Strings,andSymbols 150

"\ RG" [0342] registersans

"\ CO" [0343]copyrightsans

"\ TM" [0344] trademarksans

"\ SU" [0345]summation

NONE [0346]parenlefttp

NONE [0347]parenleftex

NONE [0350]parenleftbt

"\ lc" [0351]bracketlefttp

NONE [0352]bracketleftex

"\ lf" [0353]bracketleftbt

"\ lt" [0354]bracelefttp

"\ lk" [0355]braceleftmid

"\ lb" [0356]braceleftbt

"\ bv" [0357]braceex

"\ eu" [0360]euro

"\ ra" [0361]angleright

"\ is" [0362] integral

NONE [0363] integraltp

NONE [0364] integralex

NONE [0365] integralbt

NONE [0366]parenrighttp

NONE [0367]parenrightex

NONE [0370]parenrightbt

"\ rc" [0371]bracketrighttp

NONE [0372]bracketrightex

"\ rf" [0373]bracketrightbt

"\ RT" [0374]bracerighttp

"\ rk" [0375]bracerightmid

"\ rb" [0376]bracerightbt

Finally, thereareescapesequencesthatapplyonly if thecurrentfont is aHershey font. Mostoftheseescapesequencesprovide accessto specialsymbolsthatbelongto no font, andareaccessibleby no othermeans.Thesesymbolsareof two sorts: miscellaneous,andastronomicalor zodiacal.Theescapesequencesfor themiscellaneoussymbolsareasfollows.

"\ dd" daggerdbl

Page 156: plotutils

AppendixA: Fonts,Strings,andSymbols 151

"\ dg" dagger

"\ hb" hbar

"\ li" lineintegral

"\ IB" interbang

"\ Lb" lambdabar

"\˜ -" modifiedcongruent

"\ -+" minusplus

"\||" parallel

"\ s-" [variantform of s]

The final escapesequencein the table above, "\ s-" , yields a letter ratherthan a symbol. It isprovided becausein someHershey fonts, the shapeof the lower-caseletter‘s’ differs if it is thelast letter in a word. This is thecasefor HersheyGothicGerman.TheGermanword " besonders" ,for example,shouldbewritten as" besonder\ s-" if it is to berenderedcorrectlyin this font. Thesameis truefor thetwo Hershey symbolfonts,with theirGreekalphabets(in Greektext, lower-casefinal ‘s’ is differentfrom lower-casenon-final‘s’). In Hershey fonts wherethereis no distinctionbetweenfinal andnon-final‘s’ , " s" and"\ s-" areequivalent.

The escapesequencesfor the astronomicalsymbols,including the signsfor the twelve con-stellationsof the zodiac,are listed in the following table. We stressthat that like the precedingmiscellaneousescapesequences,they applyonly if thecurrentfont is aHershey font.

"\ SO" sun

"\ ME" mercury

"\ VE" venus

"\ EA" earth

"\ MA " mars

"\ JU" jupiter

"\ SA" saturn

"\ UR" uranus

"\ NE" neptune

"\ PL" pluto

"\ LU" moon

"\ CT" comet

"\ ST" star

"\ AS" ascendingnode

"\ DE" descendingnode

"\ AR" aries

Page 157: plotutils

AppendixA: Fonts,Strings,andSymbols 152

"\ TA" taurus

"\ GE" gemini

"\ CA" cancer

"\ LE" leo

"\ VI " virgo

"\ LI " libra

"\ SC" scorpio

"\ SG" sagittarius

"\ CP" capricornus

"\ AQ" aquarius

"\ PI" pisces

Theprecedingmiscellaneousandastronomicalsymbolsarenottheonlyspecialnon-fontsymbolsthat can be usedif the currentfont is a Hershey font. The entire library of glyphs digitized byAllen Hershey is built into GNU libplot . Sotext strings may include any Hershey glyph.Each of the available Hershey glyphs is identified by a four-digit number. StandardHersheyglyph #1wouldbespecifiedas"\ #H0001" . ThestandardHershey glyphsrangefrom "\ #H0001"to "\ #H3999" , with a numberof gaps. Someadditionalglyphs designedby othersappearinthe "\ #H4000" . . . "\ #H4194" range. Syllabic Japanesecharacters(Kana) are locatedin the"\ #H4195" . . . "\ #H4399" range.

Youmayorderatableof nearlyall theHershey glyphsin the"\ #H0001" . . . "\ #H3999" rangefrom theU.S.NationalTechnicalInformationService,at +1 7034874650. Ask for item numberPB251845;thecurrentpriceis aboutUS$40.By way of example,thestring

"\#H0744\#H0745 \# H0001\# H0002\ #H0003\ #H0869\#H 0907\# H2330 \# H2331"

when drawn will display a shamrock,a fleur-de-lys, cartographic(small) lettersA, B, C, abell,a large circle, a trebleclef, andabassclef. Again, this assumesthat thecurrentfont is a Hersheyfont.

You mayalsouseJapanesesyllabiccharacters(HiraganaandKatakana)andideographicchar-acters(Kanji) whendrawing stringsin any Hershey font. In all, 603Kanji areavailable;thesearethe sameKanji that areavailable in the HersheyEUC font. The Japanesecharactersare indexedaccordingto theJISX0208standardfor Japanesetypography, which representseachcharacterbya two-bytesequence.The file ‘kanji.doc ’, which is distributed alongwith the GNU plottingutilities, lists theavailableKanji. On mostsystemsit is installedin ‘ /usr/share/lib plo t ’ or‘ /usr/local/shar e/l ib pl ot ’.

Each JIS X0208 characterwould be specified by an escapesequencewhich expressesthis two-byte sequenceas four hexadecimal digits, such as "\ #J357e" . Both bytes mustbe in the 0x21 . . .0x7e range in order to define a JIS X0208 character. Kanji are locatedat "\ #J3021" and above. Charactersappearing elsewhere in the JIS X0208 encodingmay be accessedsimilarly. For example, Hiragana and Katakana are located in the"\ #J2421" . . . "\ #J257e" range,andRomancharactersin the "\ #J2321" . . . "\ #J237e" range.The file ‘kana.doc ’, which is installed in the samedirectory as ‘kanji.doc ’, lists theencodingsof the HiraganaandKatakana.For moreon theJIS X0208 standard,seeKenLunde’s

Page 158: plotutils

AppendixA: Fonts,Strings,andSymbols 153

UnderstandingJapaneseInformation Processing(O’Reilly, 1993), and his on-line supplement(http://www.ora. com/p eopl e/ aut hors /l unde/ cj k_ in f. htm l ).

The Kanji numberingusedin A. N. Nelson’s Modern Reader’s Japanese-EnglishCharacterDictionary, a longtimestandard,is alsosupported. (This dictionary is publishedby C. E. TuttleandCo., with ISBN 0-8048-0408-7.A revisededition [ISBN 0-8048-2036-8]appearedin 1997,but usesa different numbering.) ‘Nelson’ escapesequencesfor Kanji aresimilar to JIS X0208escapesequences,but usefour decimalinsteadof four hexadecimaldigits. Thefile ‘kanji.doc ’givesthe correspondencebetweenthe JIS numberingschemeandthe Nelsonnumberingscheme.For example, "\ #N0001" is equivalentto "\ #J306c" . It alsogivesthepositionsof theavailableKanji in theUnicodeencoding.

All available Kanji have the samewidth, which is the sameas that of the syllabic Japanesecharacters(HiraganaandKatakana). EachKanji that is not availablewill print asan ‘undefinedcharacter’glyph(a bundleof horizontallines). Thesameis truefor non-KanjiJISX0208charactersthatarenotavailable.

A.5 Availablemarker symbols

The GNU libplot library supportsa standardset of marker symbols,numbered0. . .31.A marker symbol is a visual representationof a point. The libplot marker symbolsare thesymbolsthatthegraph programwill plot ateachpoint of adataset,if the‘ -S ’ optionis specified.

Like a text string, a marker symbolhasa font size. In any output format, amarker symbol isguaranteedto be visible if its font sizeis sufficiently large. Marker symbol#0 is an exceptiontothis: by convention,symbol#0 meansno symbolat all. Marker symbolsin the range1. . .31 aredefinedasfollows.

1. dot ( ì )2. plus(+)

3. asterisk( í )4. circle ( î )5. cross( ï )

6. square

7. triangle

8. diamond

9. star

10. invertedtriangle

11. starburst

12. fancy plus

13. fancy cross

14. fancy square

15. fancy diamond

16. filled circle

17. filled square

18. filled triangle

Page 159: plotutils

AppendixA: Fonts,Strings,andSymbols 154

19. filled diamond

20. filled invertedtriangle

21. filled fancy square

22. filled fancy diamond

23. half filled circle

24. half filled square

25. half filled triangle

26. half filled diamond

27. half filled invertedtriangle

28. half filled fancy square

29. half filled fancy diamond

30. octagon

31. filled octagon

Theinterpretationof markersymbols1 through5 is thesameasin thewell known GraphicalKernelSystem(GKS).

By convention, symbols32 andup are interpretedas charactersin a certain text font. Forlibplot , thisis simplythecurrentfont. But for thegraph program,it is thesymbolfont selectedwith the‘ --symbol-font-n ame’ option. By default, thesymbolfont is theZapfDingbatsfontexcept in graph -T png , graph -T pnm, graph -T gif , graph -T pcl , graph -T hpglandgraph -T tek . Thosevariantsof graph normallyhavenoaccessto ZapfDingbatsandotherPostscriptfonts,sothey usetheHersheySerif font instead.

Many of the charactersin the ZapfDingbatsfont aresuitablefor useasmarker symbols. Forexample,character#74is theTexasstar. Doing

echo 0 0 1 2 2 1 3 2 4 0 | graph -T ps -m 0 -S 74 0.1 > plot.ps

will producea Postscriptplot consistingof fivedatapoints,not joinedby line segments.Eachdatapoint will bemarkedby a Texasstar, of a largefont size(0.1 timesthewidth of theplottingbox).

If youareusinggraph -T pcl or graph -T hpgl andwish to usefont charactersasmarkersymbols,you shouldconsiderusingtheWingdingsfont, which is availablewhenproducingPCL 5or HP-GL/2output.Doing

echo 0 0 1 2 2 1 3 2 4 0 |graph -T pcl -m 0 --symbol-font Wingdings -S 181 0.1 > plot.pcl

will producea PCL5 plot that is similar to theprecedingPostscriptplot. TheWingdingsfont hastheTexasstarin location#181.

Page 160: plotutils

AppendixB: SpecifyingColorsby Name 155

Appendix B Specifying Colors by Name

The GNU libplot library allows colors to be specifiedby the user. It includes thebgcolorname , pencolorname , andfillcolorname functions,eachof which takesacolorasanargument.

Thecommand-linegraphicsprogramsbuilt on libplot , namelygraph , plot , pic2plot ,tek2plot , and plotfont , allow colors to be specifiedon the commandline. Each ofthem supportsa ‘ --bg-color ’ option, and each of them, other than graph , supportsa‘ --pen-color ’ option. (graph supportsa morecomplicated‘ --pen-colors ’ option,anda‘ --frame-color ’ option.)

In any of thesecontexts, a color may be specifiedpreciselyasa hexadecimalstring that givesby its 48-bitRGBrepresentation.For example," #c0c0c0" is asilvery gray, and" #ffffff" is white.Also, colorsmaybespecifiedby name.665distinctnamesarerecognized,includingfamiliar oneslike" red" , " green" , and" blue" , andobscureoneslike" darkmagenta" , " forestgreen" , and" olivedrab" . Color namesarecase-insensitive, andspacesareignored. So,for example, " RosyBrown"is equivalentto " rosybrown" , and" DarkGoldenrod3" to " darkgoldenrod3" .

The file ‘colors.txt ’, which is distributed along with the GNU plotting utilities, liststhe 665 recognizedcolor names. On mostsystemsit is installedin ‘ /usr/share/libp lo t ’or ‘ /usr/local/share /li bplo t ’. The names are essentially those recognized byrecent releasesof the X Window System, which on most machinesare listed in the file‘ /usr/lib/X11/rg b.t xt ’. However, for every color namecontainingthe string " gray" ,aversioncontaining" grey" hasbeenincluded. For example, both " darkslategray4" and" darkslategrey 4" arerecognizedcolor names.

Page 161: plotutils

AppendixC: PageSizesandViewportSizes 156

Appendix C PageSizesand Viewport Sizes

When producingoutput in such formats as Illustrator, Postscript,PCL5, HP-GL, and Fig,it is important to specify the size of the pageon which the output will be printed. The GNUlibplot library allows theuserto specifya PAGESIZEparameter, which canbe usedfor this.Thecommand-linegraphicsprogramsgraph , plot , pic2plot , tek2plot , andplotfont ,whicharebuilt on libplot , supporta PAGESIZEenvironmentvariableanda ‘ --page-size ’option.

Graphicsdrawn by libplot arenominally drawn within a graphicsdisplay, or ‘viewport’.WhenproducingsuchrasterformatsasPNG,PNM, andpseudo-GIF, it will usea squareor rectan-gular bitmapasits viewport. But whenproducingIllustrator, Postscript,PCL5, HP-GL, andFigformat,it will usea squareor rectangularregion on thepageasits viewport. Exceptin theHP-GLcase,the viewport will by default be centeredon the page. Graphicswill not be clipped to theviewport,sotheentirepagewill in principlebeimageable.

Eitheror bothof thedimensionsof thegraphicsdisplaycanbespecifiedexplicitly. For example,the pagesize could be specifiedas " letter,xsize=4in" , or " a4,xsize=10cm,ysize=15cm" . Thedimensionsof the graphicsdisplayareallowed to be negative (a negative dimensionresultsin areflection).Inches,centimeters,andmillimetersarethesupportedunits.

It is also possibleto position the graphicsdisplay precisely, by specifying the location ofits lower left corner relative to the lower left cornerof the page. For example, the pagesizecould be specifiednot merely as " letter" or " a4" , but as " letter,xorigin=2in,yorigin=3in" , or" a4,xorigin=0.5cm,yorigin=0.5cm" . In all cases,the viewport position may be adjustedbyspecifyinganoffsetvector. For example,thepagesizecouldbespecifiedas" letter,yoffset=1.2in" ,or " a4,xoffset=ð 5mm,yoffset=2.0cm" . The viewport may also be rotated, by setting theROTATIONparameteror environmentvariable,or (in thecaseof thegraphicsprograms)by usingthe ‘ --rotation ’ option. A rotatedviewport doesnot changethe positionof its four corners.Rather, the graphicsare rotatedwithin it. If the viewport is rectangularratherthan square,this‘rotation’ necessarilyincludesa rescaling.

Any ISO pagesizein therange" a0" . . . " a4" or ANSI pagesizein therange" a" . . . " e" maybespecified.(" letter" is analiasfor " a" , which is thedefault, and" tabloid" is analiasfor " b" )." legal" , " ledger" , andtheJIS [JapaneseIndustrialStandard]size" b5" arerecognizedalso. Thefollowing arethesupportedpagesizesandthedefaultsquareviewportsizethatcorrespondsto each.

" a" (or " letter" ; 8.5in by 11.0in)8.0in

" b" (or " tabloid" ; 11.0in by 17.0in)10.0in

" c" (17.0in by 22.0in)16.0in

" d" (22.0in by 34.0in)20.0in

" e" (34.0in by 44.0in)32.0in

" legal" (8.5in by 14.0in)8.0in

Page 162: plotutils

AppendixC: PageSizesandViewportSizes 157

" ledger" (17.0in by 11.0in)10.0in

" a4" (21.0cm by 29.7cm)19.81cm

" a3" (29.7cm by 42.0cm)27.18cm

" a2" (42.0cm by 59.4cm)39.62cm

" a1" (59.4cm by 84.1cm)56.90cm

" a0" (84.1cm by 118.9cm)81.79cm

" b5" (18.2cm by 25.7cm)16.94cm

SVG formatandWebCGMformathave no notionof theWebpageon which theviewport willultimatelybepositioned.They do have anotionof default viewport size,thoughthis will normallybe overriddenwhentheoutputfile is placedon a Webpage. WhenproducingSVG or WebCGMoutput, this default viewport size is setby PAGESIZE, or (in the caseof the graphicsprograms)the ‘ --page-size ’ option. The " xorigin" , " yorigin" , " xoffset" , and " yoffset" specifiers,ifincluded,areignored.

For a similar reason,the " xorigin" and" yorigin" specifiersareignoredwhenproducingHP-GL or HP-GL/2output. The lower left cornerof theviewport is positionedat theHP-GL ‘scalingpoint’ P1,whoselocationisdevice-dependent. The" xoffset" and" yoffset" specifiersarerespected,however, andmaybeusedto repositiontheviewport.

Page 163: plotutils

AppendixD: TheGraphicsMetafileFormat 158

Appendix D The Graphics Metafile Format

A GNU graphicsmetafileis producedby any applicationthatusestheMetafilePlottersupportcontainedin GNU libplot . That includesthe raw variantsof graph , plot , pic2plot ,tek2plot , and plotfont . A metafile is a sort of audit trail, which specifiesa sequenceofPlotteroperations.Eachoperationis representedby an ‘op code’: asingleASCII character. Theargumentsof theoperation,if any, immediatelyfollow theop code.

A metafilemayuseeitherof two encodings:binary(thedefault) or portable(human-readable).Metafilesin the binary encodingbegin with the magicstring " #PLOT 1\ n" , andmetafilesin theportableencodingwith themagicstring" #PLOT 2\ n" . If you intendto transfermetafilesbetweenmachinesof differenttypes,you shouldusetheportableratherthanthebinaryencoding.Portablemetafilesareproducedby MetafilePlottersif theMETA_PORTABLEparameteris setto " yes" , andby the raw variantsof GNU graph and the other command-linegraphicsprogramsif the ‘ -O ’option is specified.Both binaryandportablemetafilescanbetranslatedto otherformatsby GNUplot . SeeChapter3 [plot], page27.

In theportableencoding,theargumentsof eachoperation(integers,floatingpoint numbers,orstrings)areprinted in a human-readableform, separatedby spaces,andeachargumentlist endswith a newline. In thebinaryencoding,theargumentsarerepresentedasintegers,singleprecisionfloating point numbers,or newline-terminatedASCII strings. Using the newline characteras aterminatoris acceptablebecauseeachPlotteroperationincludesa maximumof onestring amongits arguments,andsucha stringmaynot includea newline. Also, thestringmustcomelastamongthearguments.

Thereare97 Plotteroperationsin all. Themostimportantareopenpl andclosepl , whichopenandcloseaPlotter, i.e.,begin andendapageof graphics.They arerepresentedby theop codes‘o’ and‘x ’, respectively. The erase operation,if present,separatesframeswithin a page. Onreal-timedisplaydevices,it is interpretedasascreenerasure.It is representedby theopcode‘e’.

Each of the 94 other Plotter operationshas a correspondingop code, with 12 exceptions.These 12 exceptions are (1) the control operation flushpl , (2) the operationshavecap ,labelwidth , and flabelwidth , which merely return information, (3) the color ,colorname , pencolorname , fillcolorname , andbgcolorname operations,which areinternallymappedto pencolor , fillcolor , andbgcolor , (4) the frotate , fscale , andftranslate operations,which are internally mappedto fconcat , and (5) the ffontnameoperation,whichin ametafilewouldbeindistinguishablefrom fontname . Sobesides‘o’ and‘x ’,thereare83 possibleop codes, for a total of 85. Thefollowing tablelists 10 of theopcodesotherthan‘o’ and‘x ’, followedby thePlotteroperationthey standfor.

Op Code Operation

‘a’ arc

‘c ’ circle

‘e’ erase

‘ f ’ linemod

‘ l ’ line

‘m’ move

Page 164: plotutils

AppendixD: TheGraphicsMetafileFormat 159

‘n’ cont

‘p’ point

‘s ’ space

‘ t ’ label

Thefull setof 85 opcodesis listedin the libplot headerfile ‘plot.h ’ andthe libplotterheaderfile ‘plotter.h ’, whicharedistributedalongwith theplotting utilities. On mostsystemsthey areinstalledin ‘ /usr/include ’ or ‘ /usr/local/inclu de ’.

The10 op codesin the tableabove areactuallytheopcodesof the traditional‘plot(5)’ formatproducedby pre-GNUversionsof graph and libplot . Theuseof theseopcodesmake GNUmetafileformatcompatiblewith plot(5) format. Theabsenceof a magicstring,andtheabsenceofthe‘o’ and‘x ’ op codes, makesit possibleto distinguishfiles in plot(5) formatfrom GNU metafilesin thebinaryencoding.GNU plot canconvert files in plot(5) format to GNU metafilesin eitherthebinaryor theportableencoding.SeeChapter3 [plot], page27.

Page 165: plotutils

AppendixE: ObtainingAuxiliary Software 160

Appendix E Obtaining Auxiliary Software

E.1 How to get idraw

The idraw utility mentionedseveraltimesin this documentationis a freely distributableinter-activedrawing editorfor theX Window System.It candisplayandedit theoutputof any applicationthatusesthePostscriptPlottersupportcontainedin GNU libplot . Thatincludesgraph -T ps ,plot -T ps , pic2plot -T ps , tek2plot -T ps , andplotfont -T ps .

Thecurrentversionof idraw is maintainedby Vectaport,Inc.,andis availableat theirWebsite(http://www.vect apo rt .c om). It is part of the ivtools package,which is a frameworkfor building customdrawing editors. idraw wasoriginally part of the InterViews package,developedby StanfordUniversity and Silicon Graphics. The InterViews packageis avail-ableat a distribution site (ftp://interviews .st anfo rd .e du), but is no longersupported.Retrieving the ivtools packageinsteadis recommended.

Also available at Vectaport’s Web site (http://www.vecta port .co m) is an enhancedversionof idraw called drawtool . drawtool can import additionalgraphicsin TIFF andPBM/PGM/PPMformats,besidestheX11 bitmapsthat idraw canimport.

E.2 How to get xfig

Thexfig utility mentionedseveraltimesin thisdocumentationis a freelydistributableinterac-tive drawing editorfor theX Window System.It candisplayandedit theoutputof any applicationthat usesthe Fig Plotter supportcontainedin GNU libplot . That includesgraph -T fig ,plot -T fig , pic2plot -T fig , tek2plot -T fig , andplotfont -T fig .

Thecurrentversionisavailableatftp://ftp.x.org/contrib/appl ic at io ns /dr awin g_tools/ . It can import additional graphics in GIF, X11 bitmap, and Postscript formats.Accompanying the editor is a packagecalled transfig , which allows xfig graphicsto beexportedin many formats.GIF, X11 bitmap,LaTEX, andPostscriptformatsaresupported.

Thereis a Webpageon Fig format (http://duke.usa sk. ca /˜ macp hed /s of t/ fi g),whichdiscussesapplicationsoftwarethatcaninteroperatewith xfig .

Page 166: plotutils

HistoryandAcknowledgements 161

History and Acknowledgements

Severalof theGNUplottingutilitieswereinspiredbyUnix plottingutilities. A graph utility andvariousplot filterswerepresentin thefirst releasesof Unix from Bell Laboratories,goingat leastasfarbackastheVersion4 distribution (1973).Thefirst supporteddisplaydevicewasaTektronix611storagescope.Mostof thework ontying theplot filters togetherandbreakingoutdevice-dependentversionsof libplot wasperformedby Lorinda Cherry([email protected] .c om). By thetime of Version7 Unix (1979) and the subsequentBerkeley releases,the packageconsistingofgraph , plot , spline , andseveraldevice-dependentversionsof libplot wasastandardUnixfeature. Supporteddevicesby the early 1980’s includedTektronix storagescopes,early graphicsterminals,200dpi electrostaticprinter/plottersfrom Versatecand Varian, and pen plotters fromHewlett–Packard.

In 1989, Rich Murphey ([email protected] g) wrote the first GNU versionsof graph ,plot , and spline , and the earliestdocumentation.RichardStallmanfurther directeddevel-opmentof the programsand provided editorial supportfor the documentation. JohnInterrante(interran@uluru. sta nf or d. edu), thenof theInterViewsteamatStanford,generouslypro-vided the idraw Postscriptprologuenow includedin libplot , and helpful comments. Thepackageasit stoodin 1991wasdistributedunderthename‘GNU graphics’.

In 1995RobertS.Maier ([email protected] a. edu) tookoverdevelopmentof thepackage,anddesignedandwrotethecurrent, maximallydevice-independent, standaloneversionof libplot .Healsorewrotegraph from scratch,turningit into areal-timefilter thatwouldusethenew library.He fleshedout spline too,by addingsupportfor splinesin tension,periodicity, andcubicBesselinterpolation.

libplot now incorporatestheX Window Systemcodefor filling polygonsanddrawing widepolygonallines andarcs. Thecodeis usedwhenproducingoutputin bitmapformats(e.g.,PNG,PNM, andpseudo-GIF).It waswritten by Brian Kelleher, JoelMcCormack,ToddNewman,KeithPackard,RobertScheiflerandKenWhaley, who workedfor Digital EquipmentCorp.,MIT, and/ortheX Consortium, andis copyright c

ñ1985–89by theX Consortium.

Thepseudo-GIFsupportnow in libplot usesthe‘miGIF’ run-lengthencodingroutinesdevel-opedby derMaus([email protected] ontr eal. qc. ca ) andivo ([email protected] ), whicharecopyright c

ñ1998by HutchisonAvenueSoftwareCorporation(http://www.hasc. co m).

Thecopyright noticeandpermissionnoticefor themiGIF routinesaredistributedwith thesourcecodedistribution of theplottingutilities.

Mostdevelopmentwork on ode wasperformedby Nick Tufillaro ([email protected] ) in 1978–1994,on a sequenceof platformsthatextendedbackto aPDP-11runningVersion4 Unix. In 1997RobertMaier modifiedhis 1994versionto agreewith GNU conventionson codingandcommand-line parsing,extendedit to supportthe full setof specialfunctionssupportedby gnuplot , andextendedtheexceptionhandling.

Many otherpeopleaidedthedevelopmentof theplotting utilities packagealongtheway. TheHershey vectorfontsnow in libplot areof coursebasedon thecharactersdigitizedin themid tolate1960’sby Allen V. Hershey, whodeservesavoteof thanks.Additionalcharactersand/ormarkersymbolsweretakenfrom theSLAC UnifiedGraphicsSystemdevelopedby RobertC. Beachin themid-1970’s, andfrom the fonts designedby ThomasWolff ([email protected] lin .d e) forGhostscript.Theinterpolationalgorithmsusedin spline arebasedon thealgorithmsof Alan K.Cline([email protected] .e du), asdescribedin hispapersin theApr. 1974issueof Communi-

Page 167: plotutils

HistoryandAcknowledgements 162

cationsof theACM. Thetable-drivenparserusedin tek2plot waswrittenatBerkeley in themid-1980’s by EdwardMoy ([email protected] om). The ‘sagitta’ algorithmusedin anextendedform in libplot for drawing circular andelliptic arcswasdevelopedby PeterKarow of URWandKenTurkowski ([email protected] ) of Apple. RaymondToy ([email protected] .s e)helpedwith thetick markspacingcodein graph andwasthefirst to incorporateGNU getopt .Arthur Smith, formerly of LASSPat Cornell,providedcodefor his xplot utility. NelsonBeebe([email protected] .ed u) exhaustively testedthepackageinstallationprocess.

RobertMaier wrote thedocumentation,which now incorporatesNick Tufillaro’s ode manual.JulieSussmanncheckedover thedocumentationfor styleandclarity.

Page 168: plotutils

ReportingBugs 163

Reporting Bugs

Pleasereportall bugsin theGNU plottingutilities to bug-gnu-utils@ gnu.o rg . Besuretosaywhichversionof theplottingutilitiespackageyouhave. Eachcommand-lineprogramannouncesthepackageversionif youusethe‘ --version ’ argument.

If you installedthe plotting utilities from scratch,be sureto saywhat compiler(andcompilerversion)youused.If yourproblemsareinstallation-related,besureto giveall relevantinformation.