various documentation fixes
[PyX/mjg.git] / manual / graph.rst
blobced8778f6cd95202f201b32b68fc68b720a427f8
2 .. module:: graph
4 ******
5 Graphs
6 ******
9 Introduction
10 ============
12 PyX can be used for data and function plotting. At present x-y-graphs and
13 x-y-z-graphs are supported only. However, the component architecture of the
14 graph system described in section :ref:`graph_components` allows for additional
15 graph geometries while reusing most of the existing components.
17 .. % {{{
19 Creating a graph splits into two basic steps. First you have to create a graph
20 instance. The most simple form would look like::
22    from pyx import *
23    g = graph.graphxy(width=8)
25 The graph instance ``g`` created in this example can then be used to actually
26 plot something into the graph. Suppose you have some data in a file
27 :file:`graph.dat` you want to plot. The content of the file could look like:
30 .. include:: graph.dat
31    :literal:
33 To plot these data into the graph ``g`` you must perform::
35    g.plot(graph.data.file("graph.dat", x=1, y=2))
37 The method :meth:`plot` takes the data to be plotted and optionally a list of
38 graph styles to be used to plot the data. When no styles are provided, a default
39 style defined by the data instance is used. For data read from a file by an
40 instance of :class:`graph.data.file`, the default are symbols. When
41 instantiating :class:`graph.data.file`, you not only specify the file name, but
42 also a mapping from columns to axis names and other information the styles might
43 make use of (*e.g.* data for error bars to be used by the errorbar style).
45 While the graph is already created by that, we still need to perform a write of
46 the result into a file. Since the graph instance is a canvas, we can just call
47 its :meth:`writeEPSfile` method.  ::
49    g.writeEPSfile("graph")
51 The result :file:`graph.eps` is shown in figure :ref:`fig_graph`.
53 .. _fig_graph:
54 .. figure:: graph.*
55    :align:  center
57    A minimalistic plot for the data from file :file:`graph.dat`.
59 Instead of plotting data from a file, other data source are available as well.
60 For example function data is created and placed into :meth:`plot` by the
61 following line::
63    g.plot(graph.data.function("y(x)=x**2"))
65 You can plot different data in a single graph by calling :meth:`plot` several
66 times before :meth:`writeEPSfile` or :meth:`writePDFfile`. Note that a calling
67 :meth:`plot` will fail once a graph was forced to "finish" itself. This happens
68 automatically, when the graph is written to a file. Thus it is not an option to
69 call :meth:`plot` after :meth:`writeEPSfile` or :meth:`writePDFfile`. The topic
70 of the finalization of a graph is addressed in more detail in section
71 :mod:`graph.graph`. As you can see in figure :ref:`fig_graph2`, a function is
72 plotted as a line by default.
74 .. _fig_graph2:
75 .. figure:: graph2.*
76    :align:  center
78    Plotting data from a file together with a function.
80 While the axes ranges got adjusted automatically in the previous example, they
81 might be fixed by keyword options in axes constructors. Plotting only a function
82 will need such a setting at least in the variable coordinate. The following code
83 also shows how to set a logathmic axis in y-direction:
86 .. include:: graph3.py
87    :literal:
89 The result is shown in figure :ref:`fig_graph3`.
91 .. _fig_graph3:
92 .. figure:: graph3.*
93    :align:  center
95    Plotting a function for a given axis range and use a logarithmic y-axis.
98 .. _graph_components:
100 Component architecture
101 ======================
103 .. % {{{
105 Creating a graph involves a variety of tasks, which thus can be separated into
106 components without significant additional costs. This structure manifests itself
107 also in the PyX source, where there are different modules for the different
108 tasks. They interact by some well-defined interfaces. They certainly have to be
109 completed and stabilized in their details, but the basic structure came up in
110 the continuous development quite clearly. The basic parts of a graph are:
112 graph
113    Defines the geometry of the graph by means of graph coordinates with range
114    [0:1]. Keeps lists of plotted data, axes *etc.*
116 data
117    Produces or prepares data to be plotted in graphs.
119 style
120    Performs the plotting of the data into the graph. It gets data, converts them
121    via the axes into graph coordinates and uses the graph to finally plot the data
122    with respect to the graph geometry methods.
125    Responsible for the graph keys.
127 axis
128    Creates axes for the graph, which take care of the mapping from data values to
129    graph coordinates. Because axes are also responsible for creating ticks and
130    labels, showing up in the graph themselves and other things, this task is
131    splitted into several independent subtasks. Axes are discussed separately in
132    chapter :mod:`axis`.
134 .. % }}}
136 .. module:: graph.graph
138 Module :mod:`graph.graph`: Graph geometry
139 =========================================
142 The classes :class:`graphxy` and :class:`graphxyz` are part of the module
143 :mod:`graph.graph`. However, there are shortcuts to access the classes via
144 ``graph.graphxy`` and ``graph.graphxyz``, respectively.
147 .. class:: graphxy(xpos=0, ypos=0, width=None, height=None, ratio=goldenmean, key=None, backgroundattrs=None, axesdist=0.8*unit.v_cm, xaxisat=None, yaxisat=None, **axes)
149    This class provides an x-y-graph. A graph instance is also a fully functional
150    canvas.
152    The position of the graph on its own canvas is specified by *xpos* and *ypos*.
153    The size of the graph is specified by *width*, *height*, and *ratio*. These
154    parameters define the size of the graph area not taking into account the
155    additional space needed for the axes. Note that you have to specify at least
156    *width* or *height*. *ratio* will be used as the ratio between *width* and
157    *height* when only one of these is provided.
159    *key* can be set to a :class:`graph.key.key` instance to create an automatic
160    graph key. ``None`` omits the graph key.
162    *backgroundattrs* is a list of attributes for drawing the background of the
163    graph. Allowed are decorators, strokestyles, and fillstyles. ``None`` disables
164    background drawing.
166    *axisdist* is the distance between axes drawn at the same side of a graph.
168    *xaxisat* and *yaxisat* specify a value at the y and x axis, where the
169    corresponding axis should be moved to. It's a shortcut for corresonding calls of
170    :meth:`axisatv` described below. Moving an axis by *xaxisat* or *yaxisat*
171    disables the automatic creation of a linked axis at the opposite side of the
172    graph.
174    *\*\*axes* receives axes instances. Allowed keywords (axes names) are ``x``,
175    ``x2``, ``x3``, *etc.* and ``y``, ``y2``, ``y3``, *etc.* When not providing an
176    ``x`` or ``y`` axis, linear axes instances will be used automatically. When not
177    providing a ``x2`` or ``y2`` axis, linked axes to the ``x`` and ``y`` axes are
178    created automatically and *vice versa*. As an exception, a linked axis is not
179    created automatically when the axis is placed at a specific position by
180    *xaxisat* or *yaxisat*. You can disable the automatic creation of axes by
181    setting the linked axes to ``None``. The even numbered axes are plotted at the
182    top (``x`` axes) and right (``y`` axes) while the others are plotted at the
183    bottom (``x`` axes) and left (``y`` axes) in ascending order each.
185 Some instance attributes might be useful for outside read-access. Those are:
188 .. attribute:: graphxy.axes
190    A dictionary mapping axes names to the :class:`anchoredaxis` instances.
192 To actually plot something into the graph, the following instance method
193 :meth:`plot` is provided:
196 .. method:: graphxy.plot(data, styles=None)
198    Adds *data* to the list of data to be plotted. Sets *styles* to be used for
199    plotting the data. When *styles* is ``None``, the default styles for the data as
200    provided by *data* is used.
202    *data* should be an instance of any of the data described in section
203    :mod:`graph.data`.
205    When the same combination of styles (*i.e.* the same references) are used
206    several times within the same graph instance, the styles are kindly asked by the
207    graph to iterate their appearance. Its up to the styles how this is performed.
209    Instead of calling the plot method several times with different *data* but the
210    same style, you can use a list (or something iterateable) for *data*.
212 While a graph instance only collects data initially, at a certain point it must
213 create the whole plot. Once this is done, further calls of :meth:`plot` will
214 fail. Usually you do not need to take care about the finalization of the graph,
215 because it happens automatically once you write the plot into a file. However,
216 sometimes position methods (described below) are nice to be accessible. For
217 that, at least the layout of the graph must have been finished. By calling the
218 :meth:`do`\ -methods yourself you can also alter the order in which the graph
219 components are plotted. Multiple calls to any of the :meth:`do`\ -methods have
220 no effect (only the first call counts). The orginal order in which the
221 :meth:`do`\ -methods are called is:
224 .. method:: graphxy.dolayout()
226    Fixes the layout of the graph. As part of this work, the ranges of the axes are
227    fitted to the data when the axes ranges are allowed to adjust themselves to the
228    data ranges. The other :meth:`do`\ -methods ensure, that this method is always
229    called first.
232 .. method:: graphxy.dobackground()
234    Draws the background.
237 .. method:: graphxy.doaxes()
239    Inserts the axes.
242 .. method:: graphxy.doplotitem(plotitem)
244    Plots the plotitem as returned by the graphs plot method.
247 .. method:: graphxy.doplot()
249    Plots all (remaining) plotitems.
252 .. method:: graphxy.dokeyitem()
254    Inserts a plotitem in the graph key as returned by the graphs plot method.
257 .. method:: graphxy.dokey()
259    Inserts the graph key.
262 .. method:: graphxy.finish()
264    Finishes the graph by calling all pending :meth:`do`\ -methods. This is done
265    automatically, when the output is created.
267 The graph provides some methods to access its geometry:
270 .. method:: graphxy.pos(x, y, xaxis=None, yaxis=None)
272    Returns the given point at *x* and *y* as a tuple ``(xpos, ypos)`` at the graph
273    canvas. *x* and *y* are anchoredaxis instances for the two axes *xaxis* and
274    *yaxis*. When *xaxis* or *yaxis* are ``None``, the axes with names ``x`` and
275    ``y`` are used. This method fails if called before :meth:`dolayout`.
278 .. method:: graphxy.vpos(vx, vy)
280    Returns the given point at *vx* and *vy* as a tuple ``(xpos, ypos)`` at the
281    graph canvas. *vx* and *vy* are graph coordinates with range [0:1].
284 .. method:: graphxy.vgeodesic(vx1, vy1, vx2, vy2)
286    Returns the geodesic between points *vx1*, *vy1* and *vx2*, *vy2* as a path. All
287    parameters are in graph coordinates with range [0:1]. For :class:`graphxy` this
288    is a straight line.
291 .. method:: graphxy.vgeodesic_el(vx1, vy1, vx2, vy2)
293    Like :meth:`vgeodesic` but this method returns the path element to connect the
294    two points.
296 .. index::
297    single: xbasepath()@xbasepath() (graphxy method)
298    single: xvbasepath()@xvbasepath() (graphxy method)
299    single: xgridpath()@xgridpath() (graphxy method)
300    single: xvgridpath()@xvgridpath() (graphxy method)
301    single: xtickpoint()@xtickpoint() (graphxy method)
302    single: xvtickpoint()@xvtickpoint() (graphxy method)
303    single: xtickdirection()@xtickdirection() (graphxy method)
304    single: xvtickdirection()@xvtickdirection() (graphxy method)
305    single: ybasepath()@ybasepath() (graphxy method)
306    single: yvbasepath()@yvbasepath() (graphxy method)
307    single: ygridpath()@ygridpath() (graphxy method)
308    single: yvgridpath()@yvgridpath() (graphxy method)
309    single: ytickpoint()@ytickpoint() (graphxy method)
310    single: yvtickpoint()@yvtickpoint() (graphxy method)
311    single: ytickdirection()@ytickdirection() (graphxy method)
312    single: yvtickdirection()@yvtickdirection() (graphxy method)
314 .. % dirty hack to add a whole list of methods to the index:
316 Further geometry information is available by the :attr:`axes` instance variable,
317 with is a dictionary mapping axis names to :class:`anchoredaxis` instances.
318 Shortcuts to the anchoredaxis positioner methods for the ``x``\ - and ``y``\
319 -axis become available after :meth:`dolayout` as :class:`graphxy` methods
320 ``Xbasepath``, ``Xvbasepath``, ``Xgridpath``, ``Xvgridpath``, ``Xtickpoint``,
321 ``Xvtickpoint``, ``Xtickdirection``, and ``Xvtickdirection`` where the prefix
322 ``X`` stands for ``x`` and ``y``.
325 .. method:: graphxy.axistrafo(axis, t)
327    This method can be used to apply a transformation *t* to an
328    :class:`anchoredaxis` instance *axis* to modify the axis position and the like.
329    This method fails when called on a not yet finished axis, i.e. it should be used
330    after :meth:`dolayout`.
333 .. method:: graphxy.axisatv(axis, v)
335    This method calls :meth:`axistrafo` with a transformation to move the axis
336    *axis* to a graph position *v* (in graph coordinates).
338 The class :class:`graphxyz` is very similar to the :class:`graphxy` class,
339 except for its additional dimension. In the following documentation only the
340 differences to the :class:`graphxy` class are described.
343 .. class:: graphxyz(xpos=0, ypos=0, size=None, xscale=1, yscale=1, zscale=1/goldenmean, projector=central(10, -30, 30), key=None, **axes)
345    This class provides an x-y-z-graph.
347    The position of the graph on its own canvas is specified by *xpos* and *ypos*.
348    The size of the graph is specified by *size* and the length factors *xscale*,
349    *yscale*, and *zscale*. The final size of the graph depends on the projector
350    *projector*, which is called with ``x``, ``y``, and ``z`` values up to *xscale*,
351    *yscale*, and  *zscale* respectively and scaling the result by *size*. For a
352    parallel projector changing *size* is thus identical to changing *xscale*,
353    *yscale*, and *zscale* by the same factor. For the central projector the
354    projectors internal distance would also need to be changed by this factor. Thus
355    *size* changes the size of the whole graph without changing the projection.
357    *projector* defines the conversion of 3d coordinates to 2d coordinates. It can
358    be an instance of :class:`central` or :class:`parallel` described below.
360    *\*\*axes* receives axes instances as for :class:`graphxyz`. The graphxyz allows
361    for 4 axes per graph dimension ``x``, ``x2``, ``x3``, ``x4``, ``y``, ``y2``,
362    ``y3``, ``y4``, ``z``, ``z2``, ``z3``, and ``z4``. The x-y-plane is the
363    horizontal plane at the bottom and the ``x``, ``x2``, ``y``, and ``y2`` axes are
364    placed at the boundary of this plane with ``x`` and ``y`` always being in front.
365    ``x3``, ``x4``, ``y3``, and ``y4`` are handled similar, but for the top plane of
366    the graph. The ``z`` axis is placed at the origin of the ``x`` and ``y``
367    dimension, whereas ``z2`` is placed at the final point of the ``x`` dimension,
368    ``z3`` at the final point of the ``y`` dimension and ``z4`` at the final point
369    of the ``x`` and ``y`` dimension together.
372 .. attribute:: graphxyz.central
374    The central attribute of the graphxyz is the :class:`central` class. See the
375    class description below.
378 .. attribute:: graphxyz.parallel
380    The parallel attribute of the graphxyz is the :class:`parallel` class. See the
381    class description below.
383 Regarding the 3d to 2d transformation the methods :meth:`pos`, :meth:`vpos`,
384 :meth:`vgeodesic`, and :meth:`vgeodesic_el` are available as for class
385 :class:`graphxy` and just take an additional argument for the dimension. Note
386 that a similar transformation method (3d to 2d) is available as part of the
387 projector as well already, but only the graph acknowledges its size, the scaling
388 and the internal tranformation of the graph coordinates to the scaled
389 coordinates. As the projector also implements a :meth:`zindex` and a
390 :meth:`angle` method, those are also available at the graph level in the graph
391 coordinate variant (i.e. having an additional v in its name and using values
392 from 0 to 1 per dimension).
395 .. method:: graphxyz.vzindex(vx, vy, vz)
397    The depths of the point defined by *vx*, *vy*, and *vz* scaled to a range [-1:1]
398    where 1 in closed to the viewer. All arguments passed to the method are in graph
399    coordinates with range [0:1].
402 .. method:: graphxyz.vangle(vx1, vy1, vz1, vx2, vy2, vz2, vx3, vy3, vz3)
404    The cosine of the angle of the view ray thru point ``(vx1, vy1, vz1)`` and the
405    plane defined by the points ``(vx1, vy1, vz1)``, ``(vx2, vy2, vz2)``, and
406    ``(vx3, vy3, vz3)``. All arguments passed to the method are in graph coordinates
407    with range [0:1].
409 There are two projector classes :class:`central` and :class:`parallel`:
412 .. class:: central(distance, phi, theta, anglefactor=math.pi/180)
414    Instances of this class implement a central projection for the given parameters.
416    *distance* is the distance of the viewer from the origin. Note that the
417    :class:`graphxyz` class uses the range ``-xscale`` to ``xscale``, ``-yscale`` to
418    ``yscale``, and ``-zscale`` to ``zscale`` for the coordinates ``x``, ``y``, and
419    ``z``. As those scales are of the order of one (by default), the distance should
420    be of the order of 10 to give nice results. Smaller distances increase the
421    central projection character while for huge distances the central projection
422    becomes identical to the parallel projection.
424    ``phi`` is the angle of the viewer in the x-y-plane and ``theta`` is the angle
425    of the viewer to the x-y-plane. The standard notation for spheric coordinates
426    are used. The angles are multiplied by *anglefactor* which is initialized to do
427    a degree in radiant transformation such that you can specify ``phi`` and
428    ``theta`` in degree while the internal computation is always done in radiants.
431 .. class:: parallel(phi, theta, anglefactor=math.pi/180)
433    Instances of this class implement a parallel projection for the given
434    parameters. There is no distance for that transformation (compared to the
435    central projection). All other parameters are identical to the :class:`central`
436    class.
438 .. % }}}
441 .. module:: graph.data
443 Module :mod:`graph.data`: Graph data
444 ====================================
447 The following classes provide data for the :meth:`plot` method of a graph. The
448 classes are implemented in :mod:`graph.data`.
451 .. class:: file(filename, commentpattern=defaultcommentpattern, columnpattern=defaultcolumnpattern, stringpattern=defaultstringpattern, skiphead=0, skiptail=0, every=1, title=notitle, context={}, copy=1, replacedollar=1, columncallback="__column__", **columns)
453    This class reads data from a file and makes them available to the graph system.
454    *filename* is the name of the file to be read. The data should be organized in
455    columns.
457    The arguments *commentpattern*, *columnpattern*, and *stringpattern* are
458    responsible for identifying the data in each line of the file. Lines matching
459    *commentpattern* are ignored except for the column name search of the last non-
460    empty comment line before the data. By default a line starting with one of the
461    characters ``'#'``, ``'%'``, or ``'!'`` as well as an empty line is treated as a
462    comment.
464    A non-comment line is analysed by repeatedly matching *stringpattern* and,
465    whenever the stringpattern does not match, by *columnpattern*. When the
466    *stringpattern* matches, the result is taken as the value for the next column
467    without further transformations. When *columnpattern* matches, it is tried to
468    convert the result to a float. When this fails the result is taken as a string
469    as well. By default, you can write strings with spaces surrounded by ``'"'``
470    immediately surrounded by spaces or begin/end of line in the data file.
471    Otherwise ``'"'`` is not taken to be special.
473    *skiphead* and *skiptail* are numbers of data lines to be ignored at the
474    beginning and end of the file while *every* selects only every *every* line from
475    the data.
477    *title* is the title of the data to be used in the graph key. A default title is
478    constructed out of *filename* and *\*\*columns*. You may set *title* to ``None``
479    to disable the title.
481    Finally, *columns* define columns out of the existing columns from the file by a
482    column number or a mathematical expression (see below). When *copy* is set the
483    names of the columns in the file (file column names) and the freshly created
484    columns having the names of the dictionary key (data column names) are passed as
485    data to the graph styles. The data columns may hide file columns when names are
486    equal. For unset *copy* the file columns are not available to the graph styles.
488    File column names occur when the data file contains a comment line immediately
489    in front of the data (except for empty or empty comment lines). This line will
490    be parsed skipping the matched comment identifier as if the line would be
491    regular data, but it will not be converted to floats even if it would be
492    possible to convert the items. The result is taken as file column names, *i.e.*
493    a string representation for the columns in the file.
495    The values of *\*\*columns* can refer to column numbers in the file starting at
496    ``1``. The column ``0`` is also available and contains the line number starting
497    from ``1`` not counting comment lines, but lines skipped by *skiphead*,
498    *skiptail*, and *every*. Furthermore values of *\*\*columns* can be strings:
499    file column names or complex mathematical expressions. To refer to columns
500    within mathematical expressions you can also use file column names when they are
501    valid variable identifiers. Equal named items in context will then be hidden.
502    Alternatively columns can be access by the syntax ``$<number>`` when
503    *replacedollar* is set. They will be translated into function calls to
504    *columncallback*, which is a function to access column data by index or name.
506    *context* allows for accessing external variables and functions when evaluating
507    mathematical expressions for columns. Additionally to the identifiers in
508    *context*, the file column names, the *columncallback* function and the
509    functions shown in the table "builtins in math expressions" at the end of the
510    section are available.
512    Example::
514       graph.data.file("test.dat", a=1, b="B", c="2*B+$3")
516    with :file:`test.dat` looking like::
518       # A   B C
519       1.234 1 2
520       5.678 3 4
522    The columns with name ``"a"``, ``"b"``, ``"c"`` will become ``"[1.234,
523    5.678]"``, ``"[1.0, 3.0]"``, and ``"[4.0, 10.0]"``, respectively. The columns
524    ``"A"``, ``"B"``, ``"C"`` will be available as well, since *copy* is enabled by
525    default.
527    When creating several data instances accessing the same file, the file is read
528    only once. There is an inherent caching of the file contents.
530 For the sake of completeness we list the default patterns:
533 .. attribute:: file.defaultcommentpattern
535    ``re.compile(r"(#+|!+|%+)\s*")``
538 .. attribute:: file.defaultcolumnpattern
540    ``re.compile(r"\"(.*?)\"(\s+|$)")``
543 .. attribute:: file.defaultstringpattern
545    ``re.compile(r"(.*?)(\s+|$)")``
547 .. % }}}
550 .. class:: function(expression, title=notitle, min=None, max=None, points=100, context={})
552    This class creates graph data from a function. *expression* is the mathematical
553    expression of the function. It must also contain the result variable name
554    including the variable the function depends on by assignment. A typical example
555    looks like ``"y(x)=sin(x)"``.
557    *title* is the title of the data to be used in the graph key. By default
558    *expression* is used. You may set *title* to ``None`` to disable the title.
560    *min* and *max* give the range of the variable. If not set, the range spans the
561    whole axis range. The axis range might be set explicitly or implicitly by ranges
562    of other data. *points* is the number of points for which the function is
563    calculated. The points are choosen linearly in terms of graph coordinates.
565    *context* allows for accessing external variables and functions. Additionally to
566    the identifiers in *context*, the variable name and the functions shown in the
567    table "builtins in math expressions" at the end of the section are available.
569 .. % }}}
572 .. class:: paramfunction(varname, min, max, expression, title=notitle, points=100, context={})
574    This class creates graph data from a parametric function. *varname* is the
575    parameter of the function. *min* and *max* give the range for that variable.
576    *points* is the number of points for which the function is calculated. The
577    points are choosen lineary in terms of the parameter.
579    *expression* is the mathematical expression for the parametric function. It
580    contains an assignment of a tuple of functions to a tuple of variables. A
581    typical example looks like ``"x, y = cos(k), sin(k)"``.
583    *title* is the title of the data to be used in the graph key. By default
584    *expression* is used. You may set *title* to ``None`` to disable the title.
586    *context* allows for accessing external variables and functions. Additionally to
587    the identifiers in *context*, *varname* and the functions shown in the table
588    "builtins in math expressions" at the end of the section are available.
590 .. % }}}
593 .. class:: values(title="user provided values", **columns)
595    This class creates graph data from externally provided data. Each column is a
596    list of values to be used for that column.
598    *title* is the title of the data to be used in the graph key.
600 .. % }}}
603 .. class:: points(data, title="user provided points", addlinenumbers=1, **columns)
605    This class creates graph data from externally provided data. *data* is a list of
606    lines, where each line is a list of data values for the columns.
608    *title* is the title of the data to be used in the graph key.
610    The keywords of *\*\*columns* become the data column names. The values are the
611    column numbers starting from one, when *addlinenumbers* is turned on (the zeroth
612    column is added to contain a line number in that case), while the column numbers
613    starts from zero, when *addlinenumbers* is switched off.
615 .. % }}}
618 .. class:: data(data, title=notitle, context=, copy=1, replacedollar=1, columncallback="__column__", **columns)
620    This class provides graph data out of other graph data. *data* is the source of
621    the data. All other parameters work like the equally called parameters in
622    :class:`graph.data.file`. Indeed, the latter is built on top of this class by
623    reading the file and caching its contents in a :class:`graph.data.list`
624    instance.
626 .. % }}}
629 .. class:: conffile(filename, title=notitle, context=, copy=1, replacedollar=1, columncallback="__column__", **columns)
631    This class reads data from a config file with the file name *filename*. The
632    format of a config file is described within the documentation of the
633    :mod:`ConfigParser` module of the Python Standard Library.
635    Each section of the config file becomes a data line. The options in a section
636    are the columns. The name of the options will be used as file column names. All
637    other parameters work as in *graph.data.file* and *graph.data.data* since they
638    all use the same code.
640 .. % }}}
643 .. class:: cbdfile(filename, minrank=None, maxrank=None, title=notitle, context=, copy=1, replacedollar=1, columncallback="__column__", **columns)
645    This is an experimental class to read map data from cbd-files. See
646    `<http://sepwww.stanford.edu/ftp/World_Map/>`_ for some world-map data.
648 The builtins in math expressions are listed in the following table:
650 .. % }}}
652 +------------------+--------------------------------------------+
653 | name             | value                                      |
654 +==================+============================================+
655 | ``neg``          | ``lambda x: -x``                           |
656 +------------------+--------------------------------------------+
657 | ``abs``          | ``lambda x: x < 0 and -x or x``            |
658 +------------------+--------------------------------------------+
659 | ``sgn``          | ``lambda x: x < 0 and -1 or 1``            |
660 +------------------+--------------------------------------------+
661 | ``sqrt``         | ``math.sqrt``                              |
662 +------------------+--------------------------------------------+
663 | ``exp``          | ``math.exp``                               |
664 +------------------+--------------------------------------------+
665 | ``log``          | ``math.log``                               |
666 +------------------+--------------------------------------------+
667 | ``sin``          | ``math.sin``                               |
668 +------------------+--------------------------------------------+
669 | ``cos``          | ``math.cos``                               |
670 +------------------+--------------------------------------------+
671 | ``tan``          | ``math.tan``                               |
672 +------------------+--------------------------------------------+
673 | ``asin``         | ``math.asin``                              |
674 +------------------+--------------------------------------------+
675 | ``acos``         | ``math.acos``                              |
676 +------------------+--------------------------------------------+
677 | ``atan``         | ``math.atan``                              |
678 +------------------+--------------------------------------------+
679 | ``sind``         | ``lambda x: math.sin(math.pi/180*x)``      |
680 +------------------+--------------------------------------------+
681 | ``cosd``         | ``lambda x: math.cos(math.pi/180*x)``      |
682 +------------------+--------------------------------------------+
683 | ``tand``         | ``lambda x: math.tan(math.pi/180*x)``      |
684 +------------------+--------------------------------------------+
685 | ``asind``        | ``lambda x: 180/math.pi*math.asin(x)``     |
686 +------------------+--------------------------------------------+
687 | ``acosd``        | ``lambda x: 180/math.pi*math.acos(x)``     |
688 +------------------+--------------------------------------------+
689 | ``atand``        | ``lambda x: 180/math.pi*math.atan(x)``     |
690 +------------------+--------------------------------------------+
691 | ``norm``         | ``lambda x, y: math.hypot(x, y)``          |
692 +------------------+--------------------------------------------+
693 | ``splitatvalue`` | see the ``splitatvalue`` description below |
694 +------------------+--------------------------------------------+
695 | ``pi``           | ``math.pi``                                |
696 +------------------+--------------------------------------------+
697 | ``e``            | ``math.e``                                 |
698 +------------------+--------------------------------------------+
700 ``math`` refers to Pythons :mod:`math` module. The ``splitatvalue`` function is
701 defined as:
704 .. function:: splitatvalue(value, *splitpoints)
706    This method returns a tuple ``(section, value)``. The section is calculated by
707    comparing *value* with the values of splitpoints. If *splitpoints* contains only
708    a single item, ``section`` is ``0`` when value is lower or equal this item and
709    ``1`` else. For multiple splitpoints, ``section`` is ``0`` when its lower or
710    equal the first item, ``None`` when its bigger than the first item but lower or
711    equal the second item, ``1`` when its even bigger the second item, but lower or
712    equal the third item. It continues to alter between ``None`` and ``2``, ``3``,
713    etc.
715 .. % }}}
718 .. module:: graph.style
720 Module :mod:`graph.style`: Graph styles
721 =======================================
723 Please note that we are talking about graph styles here. Those are responsible
724 for plotting symbols, lines, bars and whatever else into a graph. Do not mix it
725 up with path styles like the line width, the line style (solid, dashed, dotted
726 *etc.*) and others.
728 The following classes provide styles to be used at the :meth:`plot` method of a
729 graph. The plot method accepts a list of styles. By that you can combine several
730 styles at the very same time.
732 Some of the styles below are hidden styles. Those do not create any output, but
733 they perform internal data handling and thus help on modularization of the
734 styles. Usually, a visible style will depend on data provided by one or more
735 hidden styles but most of the time it is not necessary to specify the hidden
736 styles manually. The hidden styles register themself to be the default for
737 providing certain internal data.
740 .. class:: pos(epsilon=1e-10)
742    This class is a hidden style providing a position in the graph. It needs a data
743    column for each graph dimension. For that the column names need to be equal to
744    an axis name. Data points are considered to be out of graph when their position
745    in graph coordinates exceeds the range [0:1] by more than *epsilon*.
747    .. % {{{
749 .. % }}}
752 .. class:: range(usenames=, epsilon=1e-10)
754    This class is a hidden style providing an errorbar range. It needs data column
755    names constructed out of a axis name ``X`` for each dimension errorbar data
756    should be provided as follows:
758    .. % {{{
760    +-----------+---------------------------+
761    | data name | description               |
762    +===========+===========================+
763    | ``Xmin``  | minimal value             |
764    +-----------+---------------------------+
765    | ``Xmax``  | maximal value             |
766    +-----------+---------------------------+
767    | ``dX``    | minimal and maximal delta |
768    +-----------+---------------------------+
769    | ``dXmin`` | minimal delta             |
770    +-----------+---------------------------+
771    | ``dXmax`` | maximal delta             |
772    +-----------+---------------------------+
774    When delta data are provided the style will also read column data for the axis
775    name ``X`` itself. *usenames* allows to insert a translation dictionary from
776    axis names to the identifiers ``X``.
778    *epsilon* is a comparison precision when checking for invalid errorbar ranges.
780 .. % }}}
783 .. class:: symbol(symbol=changecross, size=0.2*unit.v_cm, symbolattrs=[])
785    This class is a style for plotting symbols in a graph. *symbol* refers to a
786    (changeable) symbol function with the prototype ``symbol(c, x_pt, y_pt, size_pt,
787    attrs)`` and draws the symbol into the canvas ``c`` at the position ``(x_pt,
788    y_pt)`` with size ``size_pt`` and attributes ``attrs``. Some predefined symbols
789    are available in member variables listed below. The symbol is drawn at size
790    *size* using *symbolattrs*. *symbolattrs* is merged with ``defaultsymbolattrs``
791    which is a list containing the decorator :class:`deco.stroked`. An instance of
792    :class:`symbol` is the default style for all graph data classes described in
793    section :mod:`graph.data` except for :class:`function` and
794    :class:`paramfunction`.
796 The class :class:`symbol` provides some symbol functions as member variables,
797 namely:
800 .. attribute:: symbol.cross
802    A cross. Should be used for stroking only.
805 .. attribute:: symbol.plus
807    A plus. Should be used for stroking only.
810 .. attribute:: symbol.square
812    A square. Might be stroked or filled or both.
815 .. attribute:: symbol.triangle
817    A triangle. Might be stroked or filled or both.
820 .. attribute:: symbol.circle
822    A circle. Might be stroked or filled or both.
825 .. attribute:: symbol.diamond
827    A diamond. Might be stroked or filled or both.
829 :class:`symbol` provides some changeable symbol functions as member variables,
830 namely:
833 .. attribute:: symbol.changecross
835    attr.changelist([cross, plus, square, triangle, circle, diamond])
838 .. attribute:: symbol.changeplus
840    attr.changelist([plus, square, triangle, circle, diamond, cross])
843 .. attribute:: symbol.changesquare
845    attr.changelist([square, triangle, circle, diamond, cross, plus])
848 .. attribute:: symbol.changetriangle
850    attr.changelist([triangle, circle, diamond, cross, plus, square])
853 .. attribute:: symbol.changecircle
855    attr.changelist([circle, diamond, cross, plus, square, triangle])
858 .. attribute:: symbol.changediamond
860    attr.changelist([diamond, cross, plus, square, triangle, circle])
863 .. attribute:: symbol.changesquaretwice
865    attr.changelist([square, square, triangle, triangle, circle, circle, diamond,
866    diamond])
869 .. attribute:: symbol.changetriangletwice
871    attr.changelist([triangle, triangle, circle, circle, diamond, diamond, square,
872    square])
875 .. attribute:: symbol.changecircletwice
877    attr.changelist([circle, circle, diamond, diamond, square, square, triangle,
878    triangle])
881 .. attribute:: symbol.changediamondtwice
883    attr.changelist([diamond, diamond, square, square, triangle, triangle, circle,
884    circle])
886 The class :class:`symbol` provides two changeable decorators for alternated
887 filling and stroking. Those are especially useful in combination with the
888 :meth:`change`\ -\ :meth:`twice`\ -symbol methods above. They are:
891 .. attribute:: symbol.changestrokedfilled
893    attr.changelist([deco.stroked, deco.filled])
896 .. attribute:: symbol.changefilledstroked
898    attr.changelist([deco.filled, deco.stroked])
900 .. % }}}
903 .. class:: line(lineattrs=[])
905    This class is a style to stroke lines in a graph. *lineattrs* is merged with
906    ``defaultlineattrs`` which is a list containing the member variable
907    ``changelinestyle`` as described below. An instance of :class:`line` is the
908    default style of the graph data classes :class:`function` and
909    :class:`paramfunction` described in section :mod:`graph.data`.
911    .. % {{{
913 The class :class:`line` provides a changeable line style. Its definition is:
916 .. attribute:: line.changelinestyle
918    attr.changelist([style.linestyle.solid, style.linestyle.dashed,
919    style.linestyle.dotted, style.linestyle.dashdotted])
921 .. % }}}
924 .. class:: impulses(lineattrs=[], fromvalue=0, frompathattrs=[], valueaxisindex=1)
926    This class is a style to plot impulses. *lineattrs* is merged with
927    ``defaultlineattrs`` which is a list containing the member variable
928    ``changelinestyle`` of the :class:`line` class. *fromvalue* is the baseline
929    value of the impulses. When set to ``None``, the impulses will start at the
930    baseline. When fromvalue is set, *frompathattrs* are the stroke attributes used
931    to show the impulses baseline path.
933 .. % }}}
936 .. class:: errorbar(size=0.1*unit.v_cm, errorbarattrs=[], epsilon=1e-10)
938    This class is a style to stroke errorbars in a graph. *size* is the size of the
939    caps of the errorbars and *errorbarattrs* are the stroke attributes. Errorbars
940    and error caps are considered to be out of the graph when their position in
941    graph coordinates exceeds the range [0:1] by more that *epsilon*. Out of graph
942    caps are omitted and the errorbars are cut to the valid graph range.
944 .. % }}}
947 .. class:: text(textname="text", dxname=None, dyname=None, dxunit=0.3*unit.v_cm, dyunit=0.3*unit.v_cm, textdx=0*unit.v_cm, textdy=0.3*unit.v_cm, textattrs=[])
949    This class is a style to stroke text in a graph. The text to be written has to
950    be provided in the data column named ``textname``. *textdx* and *textdy* are the
951    position of the text with respect to the position in the graph. Alternatively
952    you can specify a ``dxname`` and a ``dyname`` and provide appropriate data in
953    those columns to be taken in units of *dxunit* and *dyunit* to specify the
954    position of the text for each point separately. *textattrs* are text attributes
955    for the output of the text. Those attributes are merged with the default
956    attributes ``textmodule.halign.center`` and ``textmodule.vshift.mathaxis``.
958 .. % }}}
961 .. class:: arrow(linelength=0.25*unit.v_cm, arrowsize=0.15*unit.v_cm, lineattrs=[], arrowattrs=[], arrowpos=0.5, epsilon=1e-10, decorator=deco.earrow)
963    This class is a style to plot short lines with arrows into a two-dimensional
964    graph to a given graph position. The arrow parameters are defined by two
965    additional data columns named ``size`` and ``angle`` define the size and angle
966    for each arrow. ``size`` is taken as a factor to *arrowsize* and *linelength*,
967    the size of the arrow and the length of the line the arrow is plotted at.
968    ``angle`` is the angle the arrow points to with respect to a horizontal line.
969    The ``angle`` is taken in degrees and used in mathematically positive sense.
970    *lineattrs* and *arrowattrs* are styles for the arrow line and arrow head,
971    respectively. *arrowpos* defines the position of the arrow line with respect to
972    the position at the graph. The default ``0.5`` means centered at the graph
973    position, whereas ``0`` and ``1`` creates the arrows to start or end at the
974    graph position, respectively. *epsilon* is used as a cutoff for short arrows in
975    order to prevent numerical instabilities. *decorator* defines the decorator to
976    be added to the line.
978 .. % }}}
981 .. class:: rect(gradient=color.gradient.Grey)
983    This class is a style to plot colored rectangles into a two-dimensional graph.
984    The size of the rectangles is taken from the data provided by the :class:`range`
985    style. The additional data column named ``color`` specifies the color of the
986    rectangle defined by *gradient*. The valid color range is [0:1].
988    .. % {{{
990 .. % }}}
993 .. class:: histogram(lineattrs=[], steps=0, fromvalue=0, frompathattrs=[], fillable=0, rectkey=0, autohistogramaxisindex=0, autohistogrampointpos=0.5, epsilon=1e-10)
995    This class is a style to plot histograms. *lineattrs* is merged with
996    ``defaultlineattrs`` which is ``[deco.stroked]``. When *steps* is set, the
997    histrogram is plotted as steps instead of the default being a boxed histogram.
998    *fromvalue* is the baseline value of the histogram. When set to ``None``, the
999    histogram will start at the baseline. When fromvalue is set, *frompathattrs* are
1000    the stroke attributes used to show the histogram baseline path.
1002    The *fillable* flag changes the stoke line of the histogram to make it fillable
1003    properly. This is important on non-steped histograms or on histograms, which hit
1004    the graph boundary. *rectkey* can be set to generate a rectanglar area instead
1005    of a line in the graph key.
1007    In the most general case, a histogram is defined by a range specification (like
1008    for an errorbar) in one graph dimension (say, along the x-axis) and a value for
1009    the other graph dimension. This allows for the widths of the histogram boxes
1010    being variable. Often, however, all histogram bin ranges are equally sized, and
1011    instead of passing the range, the position of the bin along the x-axis fully
1012    specifies the histogram - assuming that there are at least two bins. This common
1013    case is supported via two parameters: *autohistogramaxisindex*, which defines
1014    the index of the independent histogram axis (in the case just described this
1015    would be ``0`` designating the x axis). *autohistogrampointpos*, defines the
1016    relative position of the center of the histogram bin: ``0.5`` means that the bin
1017    is centered at the values passed to the style, ``0`` (``1``) means that the bin
1018    is aligned at the right-(left-)hand side.
1020    XXX describe, how to specify general histograms with varying bin widths
1022    Positions of the histograms are considered to be out of graph when they exceed
1023    the graph coordinate range [0:1] by more than *epsilon*.
1025 .. % }}}
1028 .. class:: barpos(fromvalue=None, frompathattrs=[], epsilon=1e-10)
1030    This class is a hidden style providing position information in a bar graph.
1031    Those graphs need to contain a specialized axis, namely a bar axis. The data
1032    column for this bar axis is named ``Xname`` where ``X`` is an axis name. In the
1033    other graph dimension the data column name must be equal to an axis name. To
1034    plot several bars in a single graph side by side, you need to have a nested bar
1035    axis and provide a tuple as data for nested bar axis.
1037    .. % {{{
1039    The bars start at *fromvalue* when provided. The *fromvalue* is marked by a
1040    gridline stroked using *frompathattrs*. Thus this hidden style might actually
1041    create some output. The value of a bar axis is considered to be out of graph
1042    when its position in graph coordinates exceeds the range [0:1] by more than
1043    *epsilon*.
1045 .. % }}}
1048 .. class:: stackedbarpos(stackname, addontop=0, epsilon=1e-10)
1050    This class is a hidden style providing position information in a bar graph by
1051    stacking a new bar on top of another bar. The value of the new bar is taken from
1052    the data column named *stackname*. When *addontop* is set, the values is taken
1053    relative to the previous top of the bar.
1055    .. % {{{
1057 .. % }}}
1060 .. class:: bar(barattrs=[], epsilon=1e-10, gradient=color.gradient.RedBlack)
1062    This class draws bars in a bar graph. The bars are filled using *barattrs*.
1063    *barattrs* is merged with ``defaultbarattrs`` which is a list containing
1064    ``[color.gradient.Rainbow, deco.stroked([color.grey.black])]``.
1066    .. % {{{
1068    The bar style has limited support for 3d graphs: Occlusion does not work
1069    properly on stacked bars or multiple dataset. *epsilon* is used in 3d to prevent
1070    numerical instabilities on bars without hight. When *gradient* is not ``None``
1071    it is used to calculate a lighting coloring taking into account the angle
1072    between the view ray and the bar and the distance between viewer and bar. The
1073    precise conversion is defined in the :meth:`lighting` method.
1075 .. % }}}
1078 .. class:: changebar(barattrs=[])
1080    This style works like the :class:`bar` style, but instead of the *barattrs* to
1081    be changed on subsequent data instances the *barattrs* are changed for each
1082    value within a single data instance. In the result the style can't be applied to
1083    several data instances and does not support 3d. The style raises an error
1084    instead.
1086    .. % {{{
1088 .. % }}}
1091 .. class:: gridpos(index1=0, index2=1, gridlines1=1, gridlines2=1, gridattrs=[], epsilon=1e-10)
1093    This class is a hidden style providing rectangular grid information out of graph
1094    positions for graph dimensions *index1* and *index2*. Data points are considered
1095    to be out of graph when their position in graph coordinates exceeds the range
1096    [0:1] by more than *epsilon*. Data points are merged to a single graph
1097    coordinate value when their difference in graph coordinates is below *epsilon*.
1099 .. % }}}
1102 .. class:: grid(gridlines1=1, gridlines2=1, gridattrs=[])
1104    Strokes a rectangular grid in the first grid direction, when *gridlines1* is set
1105    and in the second grid direction, when *gridlines2* is set. *gridattrs* is
1106    merged with ``defaultgridattrs`` which is a list containing the member variable
1107    ``changelinestyle`` of the :class:`line` class.
1109    .. % {{{
1111 .. % }}}
1114 .. class:: surface(colorname="color", gradient=color.gradient.Grey, mincolor=None, maxcolor=None, gridlines1=0.05, gridlines2=0.05, gridcolor=None, backcolor=color.gray.black)
1116    Draws a surface of a rectangular grid. Each rectangle is divided into 4
1117    triangles.
1119    The grid can be colored using values provided by the data column named
1120    *colorname*. The values are rescaled to the range [0:1] using mincolor and
1121    maxcolor (which are taken from the minimal and maximal values, but larger bounds
1122    could be set).
1124    If no *colorname* column exists, the surface style falls back to a lighting
1125    coloring taking into account the angle between the view ray and the triangle and
1126    the distance between viewer and triangle. The precise conversion is defined in
1127    the :meth:`lighting` method.
1129    If a *gridcolor* is set, the rectangular grid is marked by small stripes of the
1130    relative (compared to each rectangle) size of *gridlines1* and *gridlines2* for
1131    the first and second grid direction, respectively.
1133    *backcolor* is used to fill triangles shown from the back. If *backcolor* is set
1134    to ``None``, back sides are not drawn differently from the front sides.
1136    The surface is encoded using a single mesh. While this is quite space efficient,
1137    it has the following implications:
1139 * All colors must use the same color space.
1141 * HSB colors are not allowed, whereas Gray, RGB, and CMYK are allowed. You can
1142      convert HSB colors into a different color space before passing them to the
1143      surface.
1145 * The grid itself is also constructed out of triangles. The grid is transformed
1146      along with the triangles thus looking quite different from a stroked grid (as
1147      done by the grid style).
1149 * Occlusion is handled by proper painting order.
1151 * Color changes are continuous (in the selected color space) for each triangle.
1153 .. % }}}
1154 .. % }}}
1157 .. module:: graph.key
1159 Module :mod:`graph.key`: Graph keys
1160 ===================================
1162 The following class provides a key, whose instances can be passed to the
1163 constructor keyword argument ``key`` of a graph. The class is implemented in
1164 :mod:`graph.key`.
1167 .. class:: key(dist=0.2*unit.v_cm, pos="tr", hpos=None, vpos=None, hinside=1, vinside=1, hdist=0.6*unit.v_cm, vdist=0.4*unit.v_cm, symbolwidth=0.5*unit.v_cm, symbolheight=0.25*unit.v_cm, symbolspace=0.2*unit.v_cm, textattrs=[], columns=1, columndist=0.5*unit.v_cm, border=0.3*unit.v_cm, keyattrs=None)
1169    This class writes the title of the data in a plot together with a small
1170    illustration of the style. The style is responsible for its illustration.
1172    *dist* is a visual length and a distance between the key entries. *pos* is the
1173    position of the key with respect to the graph. Allowed values are combinations
1174    of ``"t"`` (top), ``"m"`` (middle) and ``"b"`` (bottom) with ``"l"`` (left),
1175    ``"c"`` (center) and ``"r"`` (right). Alternatively, you may use *hpos* and
1176    *vpos* to specify the relative position using the range [0:1]. *hdist* and
1177    *vdist* are the distances from the specified corner of the graph. *hinside* and
1178    *vinside* are numbers to be set to 0 or 1 to define whether the key should be
1179    placed horizontally and vertically inside of the graph or not.
1181    *symbolwidth* and *symbolheight* are passed to the style to control the size of
1182    the style illustration. *symbolspace* is the space between the illustration and
1183    the text. *textattrs* are attributes for the text creation. They are merged with
1184    ``[text.vshift.mathaxis]``.
1186    *columns* is a number of columns of the graph key and *columndist* is the
1187    distance between those columns.
1189    When *keyattrs* is set to contain some draw attributes, the graph key is
1190    enlarged by *border* and the key area is drawn using *keyattrs*.
1192 .. % }}} % }}}
1193 .. % vim:fdm=marker