Next: , Previous: , Up: Mathematical Packages   [Contents][Index]

5.9 Graphing


Next: , Previous: , Up: Graphing   [Contents][Index]

5.9.1 Character Plotting

(require 'charplot)

Variable: charplot:dimensions

A list of the maximum height (number of lines) and maximum width (number of columns) for the graph, its scales, and labels.

The default value for charplot:dimensions is the output-port-height and output-port-width of current-output-port.

Procedure: plot coords x-label y-label

coords is a list or vector of coordinates, lists of x and y coordinates. x-label and y-label are strings with which to label the x and y axes.

Example:

(require 'charplot)
(set! charplot:dimensions '(20 55))

(define (make-points n)
  (if (zero? n)
      '()
      (cons (list (/ n 6) (sin (/ n 6))) (make-points (1- n)))))

(plot (make-points 40) "x" "Sin(x)")
-|
  Sin(x)   _________________________________________
         1|-       ****                             |
          |      **    **                           |
      0.75|-    *        *                          |
          |    *          *                         |
       0.5|-  *            *                        |
          |  *                                     *|
      0.25|-                *                     * |
          | *                *                      |
         0|-------------------*------------------*--|
          |                                     *   |
     -0.25|-                   *               *    |
          |                     *             *     |
      -0.5|-                     *                  |
          |                       *          *      |
     -0.75|-                       *        *       |
          |                         **    **        |
        -1|-                          ****          |
          |:_____._____:_____._____:_____._____:____|
     x                 2           4           6
Procedure: plot func x1 x2
Procedure: plot func x1 x2 npts

Plots the function of one argument func over the range x1 to x2. If the optional integer argument npts is supplied, it specifies the number of points to evaluate func at.

(plot sin 0 (* 2 pi))
-|
           _________________________________________
         1|-:       ****                            |
          | :     **    **                          |
      0.75|-:    *        *                         |
          | :   *          *                        |
       0.5|-:  **          **                       |
          | : *             *                       |
      0.25|-:**              **                     |
          | :*                *                     |
         0|-*------------------*--------------------|
          | :                  *                 *  |
     -0.25|-:                   **              **  |
          | :                    *             *    |
      -0.5|-:                     *           **    |
          | :                      *          *     |
     -0.75|-:                       *       **      |
          | :                        **    **       |
        -1|-:                          ****         |
          |_:_____._____:_____._____:_____._____:___|
            0           2           4           6
Procedure: histograph data label

Creates and displays a histogram of the numerical values contained in vector or list data

(require 'random-inexact)
(histograph (do ((idx 99 (+ -1 idx))
                 (lst '() (cons (* .02 (random:normal)) lst)))
                ((negative? idx) lst))
            "normal")
-|
           _________________________________________
         8|-                :    I                  |
          |                 :    I                  |
         7|-           I  I :    I                  |
          |            I  I :    I                  |
         6|-          III I :I   I                  |
          |           III I :I   I                  |
         5|-          IIIIIIIIII I                  |
          |           IIIIIIIIII I                  |
         4|-          IIIIIIIIIIII                  |
          |           IIIIIIIIIIII                  |
         3|-I    I I  IIIIIIIIIIII  II     I        |
          | I    I I  IIIIIIIIIIII  II     I        |
         2|-I    I I IIIIIIIIIIIIIIIII     I        |
          | I    I I IIIIIIIIIIIIIIIII     I        |
         1|-II I I IIIIIIIIIIIIIIIIIIIII   I I I    |
          | II I I IIIIIIIIIIIIIIIIIIIII   I I I    |
         0|-IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII----|
          |__.____:____.____:____.____:____.____:___|
  normal        -0.025      0       0.025      0.05

Previous: , Up: Graphing   [Contents][Index]

5.9.2 PostScript Graphing

(require 'eps-graph)

This is a graphing package creating encapsulated-PostScript files. Its motivations and design choice are described in http://people.csail.mit.edu/jaffer/Docupage/grapheps

A dataset to be plotted is taken from a 2-dimensional array. Corresponding coordinates are in rows. Coordinates from any pair of columns can be plotted.

Function: create-postscript-graph filename.eps size elt1 …

filename.eps should be a string naming an output file to be created. size should be an exact integer, a list of two exact integers, or #f. elt1, ... are values returned by graphing primitives described here.

create-postscript-graph creates an Encapsulated-PostScript file named filename.eps containing graphs as directed by the elt1, ... arguments.

The size of the graph is determined by the size argument. If a list of two integers, they specify the width and height. If one integer, then that integer is the width and the height is 3/4 of the width. If #f, the graph will be 800 by 600.

These graphing procedures should be called as arguments to create-postscript-graph. The order of these arguments is significant; PostScript graphics state is affected serially from the first elt argument to the last.

Function: whole-page

Pushes a rectangle for the whole encapsulated page onto the PostScript stack. This pushed rectangle is an implicit argument to partition-page or setup-plot.


5.9.2.1 Column Ranges

A range is a list of two numbers, the minimum and the maximum. Ranges can be given explicity or computed in PostScript by column-range.

Function: column-range array k

Returns the range of values in 2-dimensional array column k.

Function: pad-range range p

Expands range by p/100 on each end.

Function: snap-range range

Expands range to round number of ticks.

Function: combine-ranges range1 range2 …

Returns the minimal range covering all range1, range2, ...

Function: setup-plot x-range y-range pagerect
Function: setup-plot x-range y-range

x-range and y-range should each be a list of two numbers or the value returned by pad-range, snap-range, or combine-range. pagerect is the rectangle bounding the graph to be drawn; if missing, the rectangle from the top of the PostScript stack is popped and used.

Based on the given ranges, setup-plot sets up scaling and margins for making a graph. The margins are sized proportional to the fontheight value at the time of the call to setup-plot. setup-plot sets two variables:

plotrect

The region where data points will be plotted.

graphrect

The pagerect argument to setup-plot. Includes plotrect, legends, etc.


5.9.2.2 Drawing the Graph

Function: plot-column array x-column y-column proc3s

Plots points with x coordinate in x-column of array and y coordinate y-column of array. The symbol proc3s specifies the type of glyph or drawing style for presenting these coordinates.

The glyphs and drawing styles available are:

line

Draws line connecting points in order.

mountain

Fill area below line connecting points.

cloud

Fill area above line connecting points.

impulse

Draw line from x-axis to each point.

bargraph

Draw rectangle from x-axis to each point.

disc

Solid round dot.

point

Minimal point – invisible if linewidth is 0.

square

Square box.

diamond

Square box at 45.o

plus

Plus sign.

cross

X sign.

triup

Triangle pointing upward

tridown

Triangle pointing downward

pentagon

Five sided polygon

circle

Hollow circle

Function: plot-text-column array x-column y-column t-column proc3s

Plots text in t-column of array at x coordinate in x-column of array and y coordinate y-column of array. The symbol proc3s specifies the offset of the text from the specified coordinates.

The offsets available are:

above

Draws the text centered above at the point.

center

Draws the text centered at the point.

below

Draws the text centered below the point.

left

Draws the text to the left of the point.

right

Draws the text to the right of the point.

All the offsets other than center are calculated to keep the text clear of a glyph drawn at the same coordinates. If you need more or less clearance, use set-glyphsize.


5.9.2.3 Graphics Context

Function: in-graphic-context arg …

Saves the current graphics state, executes args, then restores to saved graphics state.

Function: set-color color

color should be a string naming a Resene color, a saturate color, or a number between 0 and 100.

set-color sets the PostScript color to the color of the given string, or a grey value between black (0) and white (100).

Function: set-font font height
Function: set-font font encoding height

font should be a (case-sensitive) string naming a PostScript font. height should be a positive real number. encoding should name a PostScript encoding such as ‘ISOLatin1Encoding’.

set-font Changes the current PostScript font to font with the encoding encoding, and height equal to height. The default font is ‘Helvetica’ (12pt). The default encoding is ‘StandardEncoding’.

The base set of PostScript fonts is:

TimesTimes-ItalicTimes-BoldTimes-BoldItalic
HelveticaHelvetica-ObliqueHelvetica-BoldHelvetica-BoldOblique
CourierCourier-ObliqueCourier-BoldCourier-BoldOblique
Symbol

The base set of PostScript encodings is:

StandardEncodingISOLatin1EncodingExpertEncoding
ExpertSubsetEncodingSymbolEncoding

Line parameters do no affect fonts; they do effect glyphs.

Function: set-linewidth w

The default linewidth is 1. Setting it to 0 makes the lines drawn as skinny as possible. Linewidth must be much smaller than glyphsize for readable glyphs.

Function: set-linedash j k

Lines are drawn j-on k-off.

Function: set-linedash j

Lines are drawn j-on j-off.

Function: set-linedash

Turns off dashing.

Function: set-glyphsize w

Sets the (PostScript) variable glyphsize to w. The default glyphsize is 6.

The effects of clip-to-rect are also part of the graphic context.


5.9.2.4 Rectangles

A rectangle is a list of 4 numbers; the first two elements are the x and y coordinates of lower left corner of the rectangle. The other two elements are the width and height of the rectangle.

Function: whole-page

Pushes a rectangle for the whole encapsulated page onto the PostScript stack. This pushed rectangle is an implicit argument to partition-page or setup-plot.

Function: partition-page xparts yparts

Pops the rectangle currently on top of the stack and pushes xparts * yparts sub-rectangles onto the stack in decreasing y and increasing x order. If you are drawing just one graph, then you don’t need partition-page.

Variable: plotrect

The rectangle where data points should be plotted. plotrect is set by setup-plot.

Variable: graphrect

The pagerect argument of the most recent call to setup-plot. Includes plotrect, legends, etc.

Function: fill-rect rect

fills rect with the current color.

Function: outline-rect rect

Draws the perimiter of rect in the current color.

Function: clip-to-rect rect

Modifies the current graphics-state so that nothing will be drawn outside of the rectangle rect. Use in-graphic-context to limit the extent of clip-to-rect.


5.9.2.5 Legending

Function: title-top title subtitle
Function: title-top title

Puts a title line and an optional subtitle line above the graphrect.

Function: title-bottom title subtitle
Function: title-bottom title

Puts a title line and an optional subtitle line below the graphrect.

Variable: topedge
Variable: bottomedge

These edge coordinates of graphrect are suitable for passing as the first argument to rule-horizontal.

Variable: leftedge
Variable: rightedge

These edge coordinates of graphrect are suitable for passing as the first argument to rule-vertical.

Function: set-margin-templates left right

The margin-templates are strings whose displayed width is used to reserve space for the left and right side numerical legends. The default values are "-.0123456789".

Function: rule-vertical x-coord text tick-width

Draws a vertical ruler with X coordinate x-coord and labeled with string text. If tick-width is positive, then the ticks are tick-width long on the right side of x-coord; and text and numeric legends are on the left. If tick-width is negative, then the ticks are -tick-width long on the left side of x-coord; and text and numeric legends are on the right.

Function: rule-horizontal y-coord text tick-height

Draws a horizontal ruler with Y coordinate y-coord and labeled with string text. If tick-height is positive, then the ticks are tick-height long on the top side of y-coord; and text and numeric legends are on the bottom. If tick-height is negative, then the ticks are -tick-height long on the bottom side of y-coord; and text and numeric legends are on the top.

Function: y-axis

Draws the y-axis.

Function: x-axis

Draws the x-axis.

Function: grid-verticals

Draws vertical lines through graphrect at each tick on the vertical ruler.

Function: grid-horizontals

Draws horizontal lines through graphrect at each tick on the horizontal ruler.


5.9.2.6 Legacy Plotting

Variable: graph:dimensions

A list of the width and height of the graph to be plotted using plot.

Function: plot func x1 x2 npts
Function: plot func x1 x2

Creates and displays using (system "gv tmp.eps") an encapsulated PostScript graph of the function of one argument func over the range x1 to x2. If the optional integer argument npts is supplied, it specifies the number of points to evaluate func at.

Function: plot x1 x2 npts func1 func2 …

Creates and displays an encapsulated PostScript graph of the one-argument functions func1, func2, ... over the range x1 to x2 at npts points.

Function: plot coords x-label y-label

coords is a list or vector of coordinates, lists of x and y coordinates. x-label and y-label are strings with which to label the x and y axes.


5.9.2.7 Example Graph

The file am1.5.html, a table of solar irradiance, is fetched with ‘wget’ if it isn’t already in the working directory. The file is read and stored into an array, irradiance.

create-postscript-graph is then called to create an encapsulated-PostScript file, solarad.eps. The size of the page is set to 600 by 300. whole-page is called and leaves the rectangle on the PostScript stack. setup-plot is called with a literal range for x and computes the range for column 1.

Two calls to top-title are made so a different font can be used for the lower half. in-graphic-context is used to limit the scope of the font change. The graphing area is outlined and a rule drawn on the left side.

Because the X range was intentionally reduced, in-graphic-context is called and clip-to-rect limits drawing to the plotting area. A black line is drawn from data column 1. That line is then overlayed with a mountain plot of the same column colored "Bright Sun".

After returning from the in-graphic-context, the bottom ruler is drawn. Had it been drawn earlier, all its ticks would have been painted over by the mountain plot.

The color is then changed to ‘seagreen’ and the same graphrect is setup again, this time with a different Y scale, 0 to 1000. The graphic context is again clipped to plotrect, linedash is set, and column 2 is plotted as a dashed line. Finally the rightedge is ruled. Having the line and its scale both in green helps disambiguate the scales.

(require 'eps-graph)
(require 'line-i/o)
(require 'string-port)

(define irradiance
  (let ((url "http://www.pv.unsw.edu.au/am1.5.html")
        (file "am1.5.html"))
    (define (read->list line)
      (define elts '())
      (call-with-input-string line
        (lambda (iprt) (do ((elt (read iprt) (read iprt)))
                           ((eof-object? elt) elts)
                         (set! elts (cons elt elts))))))
    (if (not (file-exists? file))
        (system (string-append "wget -c -O" file " " url)))
    (call-with-input-file file
      (lambda (iprt)
        (define lines '())
        (do ((line (read-line iprt) (read-line iprt)))
            ((eof-object? line)
             (let ((nra (make-array (A:floR64b)
                                      (length lines)
                                      (length (car lines)))))
               (do ((lns lines (cdr lns))
                    (idx (+ -1 (length lines)) (+ -1 idx)))
                   ((null? lns) nra)
                 (do ((kdx (+ -1 (length (car lines))) (+ -1 kdx))
                      (lst (car lns) (cdr lst)))
                     ((null? lst))
                   (array-set! nra (car lst) idx kdx)))))
          (if (and (positive? (string-length line))
                   (char-numeric? (string-ref line 0)))
              (set! lines (cons (read->list line) lines))))))))

(let ((xrange '(.25 2.5)))
  (create-postscript-graph
   "solarad.eps" '(600 300)
   (whole-page)
   (setup-plot xrange (column-range irradiance 1))
   (title-top
    "Solar Irradiance   http://www.pv.unsw.edu.au/am1.5.html")
   (in-graphic-context
    (set-font "Helvetica-Oblique" 12)
    (title-top
     ""
     "Key Centre for Photovoltaic Engineering UNSW - Air Mass 1.5 Global Spectrum"))
   (outline-rect plotrect)
   (rule-vertical leftedge "W/(m^2.um)" 10)
   (in-graphic-context (clip-to-rect plotrect)
                       (plot-column irradiance 0 1 'line)
                       (set-color "Bright Sun")
                       (plot-column irradiance 0 1 'mountain)
                       )
   (rule-horizontal bottomedge "Wavelength in .um" 5)
   (set-color 'seagreen)

   (setup-plot xrange '(0 1000) graphrect)
   (in-graphic-context (clip-to-rect plotrect)
                       (set-linedash 5 2)
                       (plot-column irradiance 0 2 'line))
   (rule-vertical rightedge "Integrated .W/(m^2)" -10)
   ))

(system "gv solarad.eps")

Next: , Previous: , Up: Mathematical Packages   [Contents][Index]